Reco Everything you wanna value. 자세히보기

[IT|Programming]

Compiling and Running JAVA (Build System) through batch (.bat) and shell script (.sh)

kipid 2022. 12. 19. 17:25
반응형
m.logPrint() is working!

<eq> and <eqq> tags are rendered to MathJax format, being enclosed by \ ( \ ) and \ [ \ ].

docuK1 scripts started!
If this log is not closed automatically, there must be an error somewhere in your document or scripts.

Table of Contents is filled out.

Auto numberings of sections (div.sec>h2, div.subsec>h3, div.subsubsec>h4), <eqq> tags, and <figure> tags are done.

<cite> and <refer> tags are rendered to show bubble reference.

<codeprint> tags are printed to corresponding <pre> tags, only when the tags exist in the document.


Current styles (dark/bright mode, font-family, font-size, line-height) are shown.

kakao.js with id="kakao-js-sdk" is loaded.

New ShortKeys (T: Table of Contents, F: Forward Section, D: Previous Section, L: To 전체목록/[Lists]) are set.

m.delayPad=0;
m.wait=1024;
wait 528ms.
Doing delayed-load. : 2
▼ Hide
Toggle a mess
Go (FS)
TofC
DocuK Log
Backward
Forward
RRA
Lists
CmtZ
CmtX
Handle CmtZ
Log in
out focus
이 글이 도움이 되셨다면, 광고 클릭 한번씩만 부탁드립니다 =ㅂ=ㅋ.
(If this article was helpful, please click the ad once. Thank you. ;)
Mode: Bright; Font: Noto Sans KR; font-size: 18.0px (10.0); line-height: 1.6;
width: 1280, height: 720, version: 3.3.3
dg:plink (Document Global Permanent Link): https://kipid.tistory.com/207
document.referrer: Empty
This document is rendered by docuK (See also SEE (Super Easy Edit) of docuK and pure SEE).

Compiling and Running JAVA (Build System) through batch (.bat) and shell script (.sh)

Windows 에서는 batch (.bat) file 로 Mac/Unix/Linux 에서는 shell script (.sh) file 로 JAVA file 을 compile 하고 run/execute 시키는 방법.
특히나 package 가 있고 import 가 있는 java 파일을 자동으로 컴파일하고, class 파일은 따로 클래스 폴더에 넣고 그 클래스 폴더의 class 파일을 자동으로 잘 찾아서 실행시키도록 디자인.

T1.Windows

▼ Show/Hide

T1.1.batch file (runJava.bat)

관리자 권한으로 JAVA\bin 폴더에 runJava.bat 같은 batch 파일을 생성. [예] C:\Program Files\Java\jdk1.8.0_25\bin\runJava.bat.
속성 - 보안 - 사용 권한 병경 [편집] - Users/kipid - 수정 허용 체크.
Text editor 로 아래와 같이 내용을 넣고 저장.
On the left side of codes is there a hiden button to toggle/switch scrollability ({max-height:some} or {max-height:none}).
@REM encoding must be EUC-KR with Korean folder name.
@ECHO OFF

:: destination of class to be created
SET DC=C:\Recoeve\classes

:: The whole CLASSPATH list splited by ";"
SET CLASSPATH=.;C:\Program Files\Java\jdk1.8.0_25\lib;C:\Recoeve\classes;C:\Recoeve\classes\javax.mail.jar;C:\Program Files (x86)\MySQL\Connector.J 5.1\mysql-connector-java-5.1.33-bin.jar
@REM mysql-connector.jar;javax.mail.jar

:: %~nx1 expands %1 [arg 1] to "file name + extension". e.g. "HelloWorld.java"
ECHO Compiling %~nx1
:: Compile %~nx1 with {filename:%~nx1, encoding:utf8, destination:%DC%, classpath:%CLASSPATH%}
javac %~nx1 -encoding utf8 -d "%DC%" -classpath "%CLASSPATH%"

IF NOT %ERRORLEVEL%==0 GOTO :EOF

:: source directory
SET SD=%CD%
@REM or SET SD=%~dp1

:: %SD%\%~n1 gives [source directory]\file_name. e.g. "C:\Recoeve\sources\kipid\hello\HelloWorld".
SET packSD=%SD%\%~n1
@REM or SET packSD=%~dpn1

:: Replace "C:\Recoeve\sources\" to "" [empty] of %packSD%. e.g. "kipid\hello\HelloWorld".
SET CN=%packSD:C:\Recoeve\sources\=%

:: Replace "\" to "." of %cn%. e.g. "kipid.hello.HelloWorld"
:: This is a class name with JAVA package included.
SET CN=%CN:\=.%

ECHO --- OUTPUT: %CN% %2 %3 %4 %5 %6 %7 %8 %9 ---
:: Change directory to the %DC% [destination of class to be created].
CD %DC%

:: Run/Execute the class created.
java -Dfile.encoding=UTF8 -classpath "%CLASSPATH%" %CN% %2 %3 %4 %5 %6 %7 %8 %9

:: Back to source directory
CD %SD%

T1.2.Test

파일 C:\Recoeve\sources\kipid\hello\Hello.java 에 다음과 같이 저장.
package kipid.hello;

class Hello{
  public static void main(String... args){
    System.out.println("Hello World! 한글!");
    for (String arg : args) {
      System.out.println("Hello "+arg);
    }
  }
}
cmd 프롬프트에서 runJava Hello.java 를 해당파일이 위치한 폴더 C:\Recoeve\sources\kipid\hello 에서 실행하면 다음과 같이 나옴.
C:\Recoeve\sources\kipid\hello> runJava Hello.java arg1 arg2 arg3
Compiling Hello.java
--- OUTPUT: kipid.hello.Hello ---
Hello World! 한글!
Hello arg1
Hello arg2
Hello arg3

T1.3.Sublime Text 3 - Build System

Sublime Text 3 - Menu 에서 Tools - Build System - New Build System... 클릭. 아래 텍스트 복사해서 저장. 자동으로 Data\Packages\User 폴더에 저장될거임.
직접 Sublime Text 3 가 설치된 폴더에서 Data\Packages\UserrunJavaC.sublime-build 파일을 만들어서 저장해도 됨. [예] C:\Users\강수\Documents\DaumCloud\Sublime Text Build 3059 x64\Data\Packages\User\runJavaC.sublime-build.
{
  "cmd": ["runJava.bat", "$file_name"]
  // , "file_regex": "^(...*?):([0-9]*):?([0-9]*)"
  , "selector": "source.java"
  , "encoding": "utf-8" // "cp949"
}
Press Ctrl+B : Build
파일 C:\Recoeve\sources\kipid\hello\Hello.java 을 Sublime Text 에서 열고, Ctrl+B 를 누르면 자동으로 실행 됨. Tools - Build System - runJavaC 를 선택해야 할지도...
▲ Hide

T2.Mac OS, and possibly Unix/Linux

▼ Show/Hide
우선 JAVA 를 설치. 설치되면 Mac Terminal (or iTerm) 에서 다음과 같이 떠야 함. 설치할때 보통 자동으로 JAVA PATH 를 PATH 에 추가시켜 주기 때문에 어느 폴더에서 java, javac 를 실행해도 동작 하는듯.
On the left side of codes is there a hiden button to toggle/switch scrollability ({max-height:some} or {max-height:none}).
$ javac -version
javac 1.8.0_141

$ java -version
java version "1.8.0_141"
Java(TM) SE Runtime Environment (build 1.8.0_141-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.141-b15, mixed mode)



// 요 아래는 그냥 참고용으로.
$ javac
Usage: javac <options> <source files>
where possible options include:
  -g                         Generate all debugging info
  -g:none                    Generate no debugging info
  -g:{lines,vars,source}     Generate only some debugging info
  -nowarn                    Generate no warnings
  -verbose                   Output messages about what the compiler is doing
  -deprecation               Output source locations where deprecated APIs are used
  -classpath <path>          Specify where to find user class files and annotation processors
  -cp <path>                 Specify where to find user class files and annotation processors
  -sourcepath <path>         Specify where to find input source files
  -bootclasspath <path>      Override location of bootstrap class files
  -extdirs <dirs>            Override location of installed extensions
  -endorseddirs <dirs>       Override location of endorsed standards path
  -proc:{none,only}          Control whether annotation processing and/or compilation is done.
  -processor <class1>[,<class2>,<class3>...] Names of the annotation processors to run; bypasses default discovery process
  -processorpath <path>      Specify where to find annotation processors
  -parameters                Generate metadata for reflection on method parameters
  -d <directory>             Specify where to place generated class files
  -s <directory>             Specify where to place generated source files
  -h <directory>             Specify where to place generated native header files
  -implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files
  -encoding <encoding>       Specify character encoding used by source files
  -source <release>          Provide source compatibility with specified release
  -target <release>          Generate class files for specific VM version
  -profile <profile>         Check that API used is available in the specified profile
  -version                   Version information
  -help                      Print a synopsis of standard options
  -Akey[=value]              Options to pass to annotation processors
  -X                         Print a synopsis of nonstandard options
  -J<flag>                   Pass <flag> directly to the runtime system
  -Werror                    Terminate compilation if warnings occur
  @<filename>                Read options and filenames from file



$ java
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
    -d32    use a 32-bit data model if available
    -d64    use a 64-bit data model if available
    -server    to select the "server" VM
                  The default VM is server,
                  because you are running on a server-class machine.


    -cp <class search path of directories and zip/jar files>
    -classpath <class search path of directories and zip/jar files>
                  A : separated list of directories, JAR archives,
                  and ZIP archives to search for class files.
    -D<name>=<value>
                  set a system property
    -verbose:[class|gc|jni]
                  enable verbose output
    -version      print product version and exit
    -version:<value>
                  Warning: this feature is deprecated and will be removed
                  in a future release.
                  require the specified version to run
    -showversion  print product version and continue
    -jre-restrict-search | -no-jre-restrict-search
                  Warning: this feature is deprecated and will be removed
                  in a future release.
                  include/exclude user private JREs in the version search
    -? -help      print this help message
    -X            print help on non-standard options
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  enable assertions with specified granularity
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  disable assertions with specified granularity
    -esa | -enablesystemassertions
                  enable system assertions
    -dsa | -disablesystemassertions
                  disable system assertions
    -agentlib:<libname>[=<options>]
                  load native agent library <libname>, e.g. -agentlib:hprof
                  see also, -agentlib:jdwp=help and -agentlib:hprof=help
    -agentpath:<pathname>[=<options>]
                  load native agent library by full pathname
    -javaagent:<jarpath>[=<options>]
                  load Java programming language agent, see java.lang.instrument
    -splash:<imagepath>
                  show splash screen with specified image
See <a target="_blank" href="http://www.oracle.com/technetwork/java/javase/documentation/index.html">http://www.oracle.com/technetwork/java/javase/documentation/index.html</a> for more details.

T2.1.shell script (runJava.sh)

다음과 같은 shell script file 을 만들고 저장.
#!/bin/sh
# chmod 755 runJava.sh
# cp runJava.sh /usr/local/bin/
FILE_BASE_NAME=$1
if [ -f "${FILE_BASE_NAME}.java" ]; then
  echo $PWD # Print Working Directory.
  PACKAGE=$2
  D=$3
  CLASSPATH=.:/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home/jre/lib:${D}
  echo "Compiling ${FILE_BASE_NAME}.java"
  javac ${FILE_BASE_NAME}.java -encoding utf8 -d ${D} -classpath ${CLASSPATH}
else
  echo "File ${FILE_BASE_NAME}.java does not exist."
fi
if [ $? == 0 ]; then
  cd $D
  CLASSFILE=./${PACKAGE//./\/}/${FILE_BASE_NAME}
  if [ -f "${CLASSFILE}.class" ]; then
    echo "--- OUTPUT: ${PACKAGE}.${FILE_BASE_NAME} $4 $5 $6 $7 $8 $9 ---"
    java -Dfile.encoding=UTF8 -classpath ${CLASSPATH} ${PACKAGE}.${FILE_BASE_NAME} $4 $5 $6 $7 $8 $9
  else
    echo "File ${CLASSFILE}.class does not exist."
  fi
fi
Mac Terminal (or iTerm) 에서 runJava.sh 에 실행권한을 주고, /usr/local/bin/ 폴더로 복사.

$ chmod 755 runJava.sh
$ cp runJava.sh /usr/local/bin/

T2.2.Test

파일 /Users/kipid/Documents/sources/kipid/hello/Hello.java 에 다음과 같이 저장.
package kipid.hello;

import java.lang.Math;

public class Hello {
  public static void main(String... args) {
    System.out.println("Hello World! 한글!");
    for (String arg : args) {
      System.out.println("Hello "+arg);
    }
    System.out.println(System.getProperty("java.class.path"));
    System.out.println(System.getProperty("java.home"));
    System.out.println(System.getProperty("user.dir"));
    System.out.println(System.getProperty("user.name"));
    System.out.println(System.getProperty("user.home"));
    System.out.println(Math.abs(-1));
  }
}
다음과 같이 실행하면 됨. (첫번째 argument 로 file_base_name 을, 두번째로 package, 세번째로 class 파일을 저장할 destination, 그 다음부터는 JAVA 파일 실행시 넘겨줄 arguments 를...)
$ runJava.sh Hello kipid.hello /Users/kipid/Documents/classes arg1 arg2 arg3
/Users/kipid/Documents/sources/kipid/hello
Compiling Hello.java
--- OUTPUT: kipid.hello.Hello arg1 arg2 arg3    ---
Hello World! 한글!
Hello arg1
Hello arg2
Hello arg3
.:/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home/jre/lib:/Users/kipid/Documents/classes
/Library/Java/JavaVirtualMachines/jdk1.8.0_141.jdk/Contents/Home/jre
/Users/kipid/Documents/classes
kipid
/Users/kipid
1

T2.3.Sublime Text 3 - Build System

{
  "cmd": ["runJava.sh"
      , "$file_base_name" // $1 : file_base_name
      , "kipid.hello" // $2 : package
      , "/Users/kipid/Documents/classes" // $3 : -d (destination)
      , "arg1", "arg2", "arg3" // $4 ...
  ]
  , "path": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
  // , "file_regex": "^(...*?):([0-9]*):?([0-9]*)"
  , "selector": "source.java"
  , "encoding": "utf-8"
}
Press Command+B : Build
▲ Hide
Toggle a mess
* 홍보/Promoting Recoeve.net (3S | Slow/Sexy/Sincere SNS)
유튜브 음악, K-Pop MV 들을 광고없이 목록재생 해서 보세요.
접속하셔서 가입 후 별점만 드레그 하시면 자신의 페이지에 저장 됩니다.
그리고 자신의 페이지로 이동한 뒤 추천 받기 (단축키 R) 를 누르시면 자신이 점수 메긴것들로 이웃 (이웃보기 단축키 B) 을 자동으로 찾아주고 그 이웃들로부터 추천을 받을 수 있습니다.
Toggle a mess
이 글이 도움이 되셨다면, 광고 클릭 한번씩만 부탁드립니다 =ㅂ=ㅋ.
(If this article was helpful, please click the ad once. Thank you. ;)
반응형