🧑‍💻복습/자바

자바 gitignore, gradle UTF-8 실행하기

우동한그릇 2023. 5. 25. 17:26
반응형

 

 

git 허브에 push 할 때 gitingnore 을 설정해주기

 

https://www.toptal.com/developers/gitignore

 

gitignore.io

Create useful .gitignore files for your project

www.toptal.com

 

Java 웹프로젝트를 할 때 위와 같이 기본적으로 gitignore 을 생성하여

github에 Class 파일 등이 업로드 되지 않게 해주는 것이 목적이다.

class 파일을 github에 업로드 하는 것이 권장되지 않는 이유는 다음과 같다.

 

가독성: 클래스 파일은 이진 형식이기 때문에 사람이 직접 읽기 어렵습니다. 따라서, 다른 개발자나 협업자가 클래스 파일을 이해하고 변경하기 어려울 수 있습니다. 소스 코드를 공유하면 다른 개발자들이 코드를 이해하고 수정할 수 있으며, 코드 리뷰나 협업이 원활하게 이루어질 수 있습니다.

보안: 클래스 파일은 실행 가능한 파일이므로 민감한 정보나 알고리즘 등이 포함될 수 있습니다. 이러한 정보가 공개되면 보안상의 문제가 발생할 수 있습니다. 소스 코드를 공개하고 필요한 보안 조치를 적용하는 것이 좋습니다.

빌드 환경 의존성: 클래스 파일은 특정 환경에서 컴파일된 코드이므로, 다른 환경에서 실행될 수 없을 수 있습니다. 개발자들은 소스 코드를 컴파일하여 각자의 빌드 환경에 맞는 실행 가능한 파일을 생성해야 합니다.

 

※ 단, 이미 올라간 데이터는 절대 완전 삭제할 수 없다. 중요한 정보가 포함된 파일이라고해도 

    지정된 위치에 히스토리에는 반드시 존재하게된다. git은 조작을 못하게 하는 것이 목표이다.

 

 

위 사진과 같이 설정하여 생성해주면 다음과 같이 코드가 출력된다.

 

# Created by https://www.toptal.com/developers/gitignore/api/java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node
# Edit at https://www.toptal.com/developers/gitignore?templates=java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node

### C++ ###
# Prerequisites
*.d

# Compiled Object files
*.slo
*.lo
*.o
*.obj

# Precompiled Headers
*.gch
*.pch

# Compiled Dynamic libraries
*.so
*.dylib
*.dll

# Fortran module files
*.mod
*.smod

# Compiled Static libraries
*.lai
*.la
*.a
*.lib

# Executables
*.exe
*.out
*.app

### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders

# External tool builders
.externalToolBuilders/

# Locally stored "Eclipse launch configurations"
*.launch

# PyDev specific (Python IDE for Eclipse)
*.pydevproject

# CDT-specific (C/C++ Development Tooling)
.cproject

# CDT- autotools
.autotools

# Java annotation processor (APT)
.factorypath

# PDT-specific (PHP Development Tools)
.buildpath

# sbteclipse plugin
.target

# Tern plugin
.tern-project

# TeXlipse plugin
.texlipse

# STS (Spring Tool Suite)
.springBeans

# Code Recommenders
.recommenders/

# Annotation Processing
.apt_generated/
.apt_generated_test/

# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet

# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project

### Eclipse Patch ###
# Spring Boot Tooling
.sts4-cache/

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# SonarLint plugin
.idea/sonarlint/

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr

# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/

# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml

# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/

# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$

# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml

# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml

### Java ###
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*

### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### macOS Patch ###
# iCloud generated files
*.icloud

### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar

# Eclipse m2e generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath

### Node ###
# Logs
logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### Node Patch ###
# Serverless Webpack directories
.webpack/

# Optional stylelint cache

# SvelteKit build / generate output
.svelte-kit

### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets

# Local History for Visual Studio Code
.history/

# Built Visual Studio Code Extensions
*.vsix

### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide

### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

### Gradle ###
.gradle
**/build/
!src/**/build/

# Ignore Gradle GUI config
gradle-app.setting

# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar

# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties

# Cache of project
.gradletasknamecache

# Eclipse Gradle plugin generated files
# Eclipse Core
# JDT-specific (Eclipse Java Development Tools)

### Gradle Patch ###
# Java heap dump
*.hprof

# End of https://www.toptal.com/developers/gitignore/api/java,c++,windows,macos,eclipse,intellij,visualstudiocode,gradle,maven,node

 

위 코드를 .gitignore 파일 안에 전체 붙여넣기 해주면 된다.

 

 

적용 후 자동으로 Hello.class 파일이 회색으로 변하면 성공적으로 gitignore이 적용 된 것이다.

 

 

git push 명령어를 통해서 github에 업로드 해보았다. 

 

 

repo를 확인해보면 .class 파일은 업로드 되지 않은 것을 확인할 수 있다.

 

 

요약하자면, github에 push 할 때 class 파일은 보안 및 가독성의 이유로 포함되지않게 해주어야하며

.gitignore 설정 파일에 toptal 사이트에서 받은 코드를 추가해줌으로써 적용할 수 있고, 이를 확인해보았다.

 

혹시 오류가 나타나는 경우 !

 

git clone 은 원격 저장소를 로컬로 복제하는 명령이다. 

이때 , 원격저장소에 readme file이 있거나 다른 파일이 이미 존재해서 오류가 나오는 경우가 발생했다.

아래와 같이 명령어를 입력해주어 해결했다.

 

git push -f origin main

 

해당 명령어를 통해 강제로 원격 저장소에 푸시하는 명령어를 통해서 덮어쓰기해주게된다.

단, 중요한 파일은 백업해두어야한다. (사실 무언가 더 좋은 방법이 있을 거라 생각한다.)

 

git pull origin main

 

원격저장소와 clone으로 연결되어있을 때 업데이트 해주는 방법.

여기서 반드시 원격저장소와 폴더 경로가 일치해야한다.

 

 


VScode JAVA Tab키 간격 적용이 안될 때 !

 

settings 에서 indentation 을 검색하고 체크를 해제하여 Java 에서 탭키를 스페이스바 두번으로 바꿔줄 수 있다.

 


Gradle run 으로 java 파일 컴파일 없이 바로 실행시켜보기

App.java 파일 만들기

 

App.java 코드를 작성하고 App.java  파일을 만들어준다.

 

package bitcamp.myapp;

public class App {
  public static void main(String[] args) {
    System.out.println("나의 목록 관리 시스템");
    System.out.println("----------------------");

    System.out.println("번호: ");
    System.out.println("100");

    System.out.printf("이름: %s\n", "홍길동");
    System.out.println();

    System.out.println("나이: " + 20);

    System.out.printf("재직자: %b\n", true);

    System.out.printf("성별(남자(M), 여자(W)): %c\n", 'M');

    System.out.printf("좌우시력: %.1f, %.1f\n", 1.5f, 1.0f);
  }
}

 

 

grand init 과 buid 적용하기

https://dev-with-gpt.tistory.com/71

 

자바 웹프로그래밍 Git clone, Gradle, 컴파일 실행

* Git clone 명령어 "git clone"은 Git 버전 관리 시스템에서 원격 저장소의 프로젝트를 로컬 환경으로 복제하는 명령어 Git을 사용하여 프로젝트를 공유하고 협업하기 위해 중앙 원격 저장소에 프로젝

dev-with-gpt.tistory.com

gradle이 성공하였다면 buid.gradle이 myapp에 생성되었을 것이다.

windosw에서는 기본적으로 UTF-8 실행이 지원되지 않기 때문에

build.gradle 에 아래 코드로 변경해서 적용해주어야한다.

 

plugins {
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'

    implementation 'com.google.guava:guava:31.1-jre'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

application {
    mainClass = 'bitcamp.myapp.App'
}

tasks.named('test') {
    useJUnitPlatform()
}

// 자바 소스를 컴파일 할 때 적용할 옵션
tasks.withType(JavaCompile) {
    // 프로젝트의 소스 파일 인코딩을 gradle에게 알려준다.
    // $javac -encoding UTF-8 ..
    options.encoding = 'UTF-8' 

    // 소스 파일을 작성할 때 사용할 자바 버전
    sourceCompatibility = '17'

    // 자바 클래스를 실행시킬 JVM의 최소 버전
    targetCompatibility = '17'
}

 

gradl -q run 으로 작동시켜보면 성공적으로 출력되는 것을 확인할 수 있다.

 

 

반응형