- Java and windows cmd
- Работа с Java в командной строке
- От простого к .
- Один файл
- Отделяем бинарные файлы от исходников
- Используем пакеты
- Если в программе несколько файлов
- Если удивляет результат
- Хорошо бы протестировать
- Создадим библиотеку
- Надо узнать, что у библиотеки внутри
- Лучше снабдить библиотеку документацией
- Можно подписать jar-архив
- Использование библиотеки
- Собираем программу
- Первый способ
- Второй способ
- Третий способ
- Запуск исполняемого jar-файла
- Как быть с приложениями JavaEE
- How do I run a Java program from the command line on Windows?
- 12 Answers 12
Java and windows cmd
This page is obsolete.
This document instructs you on how to use the Windows Command Prompt with Java. These instructions are specialized to Windows 7, but are similar for Windows XP and Windows Vista.
You will use the Java compiler javac to compile your Java programs and the Java interpreter java to run them. You should skip the first step if Java is already installed on your machine.
- Download and install the latest version of the Java Platform, Standard Edition Development Kit (Java SE 6 Update 27). Note the installation directory for later—probably something like C:\Program Files\Java\jdk1.6.0_27\bin.
To make sure that Windows can find the Java compiler and interpreter:
Select Start -> Computer -> System Properties -> Advanced system settings -> Environment Variables -> System variables -> PATH. Control Panel -> System and Security -> Programs -> Advanced -> Environment Variables -> PATH —>
Control Panel -> System and Maintenance -> System -> Advanced System Settings -> Advanced -> Environment variables -> PATH. ] —> [ In Vista, select Start -> My Computer -> Properties -> Advanced -> Environment Variables -> System variables -> PATH. ]
[ In Windows XP, Select Start -> Control Panel -> System -> Advanced -> Environment Variables -> System variables -> PATH. ]
Prepend C:\Program Files\Java\jdk1.6.0_27\bin; to the beginning of the PATH variable.
Command-line interface |
You will type commands in an application called the Command Prompt.
- Launch the command prompt via All Programs -> Accessories -> Command Prompt. (If you already had a command prompt window open, close it and launch a new one.) You should see the command prompt; it will look something like:
To check that you have the right version of Java installed, type the text in boldface below. You should see something similar to the information printed below. (It’s important that you see the number 1.6 or 1.5 for the Java version number, but the rest is not critical.)
Since you will be using the Command Prompt frequently, we recommend customizing the default settings. Right-click the title bar of an open Command Prompt window, select Properties and then:
Window Size to 80 x 25. —>
Set Layout -> Screen Buffer Size to 80 x 500.
Select Options -> Edit Options -> QuickEdit Mode.
Compile the Program |
You will use the javac command to convert your Java program into a form more amenable for execution on a computer.
From the Command Prompt, navigate to the directory containing your .java files, say C:\introcs\hello, by typing the cd command below.
Execute the Program |
You will use the java command to execute your program.
- From the Command Prompt, type the java command below.
Input and Output |
If your program gets stuck in an infinite loop, type Ctrl-c to break out.
If you are entering input from the keyboard, you can signify to your program that there is no more data by typing Ctrl-z for EOF (end of file). On some DOS systems the first line of output sent to the screen after you enter EOF will be rendered invisible by DOS. This is not a problem with your code, but rather a problem with DOS. To help you debug your program, we recommend including an extra System.out.println(); statement before what you really want to print out. If anyone knows of a better fix, please let us know!
Troubleshooting |
Here are a few suggestions that might help correct any installation woes you are experiencing. If you need assistance, don’t hesitate to contact a staff member.
When I type, «java -version» I get an error. Check that you edited your PATH environment variable as indicated. A missing ; or an added % is enough to screw things up. Close and re-open a command prompt. Type path at the command prompt and look for an entry that includes C:\Program Files\Java\jdk1.6.0_27\bin;. Check that the version number 1.6.0_27 matches the one you installed—Oracle updates Java periodically and you might have a more recent version. If this doesn’t fix the problem, check if you have any old versions of Java on your system. If so, un-install them and re-install Java.
The command «java -version» works, but not «javac -version». Any thoughts? It’s likely a path issue. Try the suggestions from the previous question. Also check that you installed the JDK properly by checking that the folder C:\Program Files\Java\jdk1.6.0_27\bin exists.
How can I check the values of my PATH variable? Type the following at the command prompt.
I can compile with javac, but I get the error message «Exception in thread «main» java.lang.NoClassDefFoundError: HelloWorld» when I try to execute it with java. First, be sure that HelloWorld.class is now in the current directory. Be sure to type java HelloWorld without a trailing .class or .java. Check that the command «java -version» works. Now try to execute with «java -cp . HelloWorld«. If this works, you need to edit your classpath. (iTunes has a proclivity for changing the classpath, so if you recently upgraded iTunes, this is likely the source of the problem.)
Where can I learn more about the Windows command line? Here is a short tutorial on the Windows command prompt. Microsoft maintains a complete command line reference.
How do I change my directory to the H: drive from the Windows Command Prompt? Type H: at the command prompt. Then cd to the appropriate directory.
Работа с Java в командной строке
От простого к .
Каждая программа обычно содержится в отдельном каталоге. Я придерживаюсь правила создавать в этом каталоге по крайней мере две папки: src и bin. В первой содержатся исходные коды, во второй — результат компиляции. В данных папках будет структура каталогов, зависящая от пакетов.
Один файл
Можно сделать и без лишних папок.
Берем сам файл HelloWorld.java.
Переходим в каталог, где лежит данный файл, и выполняем команды.
В данной папке появится файл HelloWorld.class. Значит программа скомпилирована. Чтобы запустить
Отделяем бинарные файлы от исходников
Теперь сделаем тоже самое, но с каталогами. Создадим каталог HelloWorld и в нем две папки src и bin.
Компилируем
Здесь мы указали, что бинарные файлы будут сохраняться в отдельную папку bin и не путаться с исходниками.
Используем пакеты
А то, вдруг, программа перестанет быть просто HelloWorld-ом. Пакетам лучше давать понятное и уникальное имя. Это позволит добавить данную программу в другой проект без конфликта имен. Прочитав некоторые статьи, можно подумать, что для имени пакета обязательно нужен домен. Это не так. Домены — это удобный способ добиться уникальности. Если своего домена нет, воспользуйтесь аккаунтом на сайте (например, ru.habrahabr.mylogin). Он будет уникальным. Учтите, что имена пакетов должны быть в нижнем регистре. И избегайте использования спецсимволов. Проблемы возникают из-за разных платформ и файловых систем.
Поместим наш класс в пакет с именем com.qwertovsky.helloworld. Для этого добавим в начало файла строчку
В каталоге src создадим дополнительные каталоги, чтобы путь к файлу выглядел так: src/com/qwertovsky/helloworld/HelloWorld.java.
Компилируем
В каталоге bin автоматически создастся структура каталогов как и в src.
Если в программе несколько файлов
HelloWorld.java
Calculator.java
Adder.java
Ошибка возникла из-за того, что для компиляции нужны файлы с исходными кодами классов, которые используются (класс Calculator). Надо указать компилятору каталог с файлами с помощью ключа -sourcepath.
Компилируем
Если удивляет результат
Есть возможность запустить отладчик. Для этого существует jdb.
Сначала компилируем с ключом -g, чтобы у отладчика была информация.
Отладчик запускает свой внутренний терминал для ввода команд. Справку по последним можно вывести с помощью команды help.
Указываем точку прерывания на 9 строке в классе Calculator
Запускаем на выполнение.
Чтобы соориентироваться можно вывести кусок исходного кода, где в данный момент находится курссор.
Узнаем, что из себя представляет переменная а.
Выполним код в текущей строке и увидим, что sum стала равняться 2.
Поднимемся из класса Adder в вызвавший его класс Calculator.
Удаляем точку прерывания
Можно избежать захода в методы, используя команду next.
Проверяем значение выражения и завершаем выполнение.
Хорошо бы протестировать
Запускаем. В качестве разделителя нескольких путей в classpath в Windows используется ‘;’, в Linux — ‘:’. В консоли Cygwin не работают оба разделителя. Возможно, должен работать ‘;’, но он воспринимается как разделитель команд.
Создадим библиотеку
Класс Calculator оказался полезным и может быть использован во многих проектах. Перенесем всё, что касается класса Calculator в отдельный проект.
Измените также назавания пакетов в исходных текстах. В HelloWorld.java нужно будет добавить строку
Делаем архив jar
С помощью ключа -C мы запустили программу в каталоге bin.
Надо узнать, что у библиотеки внутри
Можно распаковать архив zip-распаковщиком и посмотреть, какие классы есть в библиотеке.
Информацию о любом классе можно получить с помощью дизассемблера javap.
Из результата видно, что класс содержит кроме пустого конструктора, ещё один метод sum, внутри которого в цикле вызывается метод add класса Adder. По завершении метода sum, вызывается Adder.getSum().
Без ключа -c программа выдаст только список переменных и методов (если использовать -private, то всех).
Лучше снабдить библиотеку документацией
Изменим для этого класс калькулятора.
Документацию можно создать следующей командой. При ошибке программа выдаст список возможных опций.
В результате получиться следующее
Можно подписать jar-архив
Если требуется подписать свою библиотеку цифровой подписью, на помощь придут keytool и jarsigner.
Генерируем подпись.
Генерируем Certificate Signing Request (CSR)
Содержимое полученного файла отправляем в центр сертификации. От центра сертификации получаем сертификат. Сохраняем его в файле (например, qwertokey.cer) и импортируем в хранилище
Файл qwertokey.cer отправляем всем, кто хочет проверить архив. Проверяется он так
Использование библиотеки
Есть программа HelloWorld, которая использует библиотечный класс Calculator. Чтобы скомпилировать и запустить программу, нужно присоединить библиотеку.
Компилируем
Собираем программу
Это можно сделать по-разному.
Первый способ
Здесь есть тонкости.
В строке
не должно быть пробелов в конце.
Вторая тонкость описана в [3]: в этой же строке должен стоять перенос на следующую строку. Это если манифест помещается в архив сторонним архиватором.
Программа jar не включит в манифест последнюю строку из манифеста, если в конце не стоит перенос строки.
Ещё момент: в манифесте не должно быть пустых строк между строками. Будет выдана ошибка «java.io.IOException: invalid manifest format».
При использовании команды echo надо следить только за пробелом в конце строки с main-class.
Второй способ
В данном способе избегаем ошибки с пробелом в main-class.
Третий способ
Включили код нужной библиотеки в исполняемый файл.
Запуск исполняемого jar-файла
Файл calculator.jar исполняемым не является. А вот helloworld.jar можно запустить.
Если архив был создан первыми двумя способами, то рядом с ним в одном каталоге должна находится папка lib с файлом calculator.jar. Такие ограничения из-за того, что в манифесте в class-path указан путь относительно исполняемого файла.
При использовании третьего способа нужные библиотеки включаются в исполняемый файл. Держать рядом нужные библиотеки не требуется. Запускается аналогично.
Как быть с приложениями JavaEE
Аналогично. Только библиотеки для компиляции нужно брать у сервера приложений, который используется. Если я использую JBoss, то для компиляции сервлета мне нужно будет выполнить примерно следующее
Структура архива JavaEE-приложения должна соответствовать определенному формату. Например
Способы запуска приложения на самом сервере с помощью командной строки для каждого сервера различны.
Надеюсь, данная статья станет для кого-нибудь шпаргалкой для работы с Java в командной строке. Данные навыки помогут понять содержание и смысл Ant-скриптов и ответить на собеседовании на более каверзные вопросы, чем «Какая IDE Вам больше нравится?».
How do I run a Java program from the command line on Windows?
I’m trying to execute a Java program from the command line in Windows. Here is my code:
I’m not sure how to execute the program — any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?
12 Answers 12
Let’s say your file is in C:\mywork\
Run Command Prompt
This makes C:\mywork the current directory.
This displays the directory contents. You should see filenamehere.java among the files.
This tells the system where to find JDK programs.
This runs javac.exe, the compiler. You should see nothing but the next system prompt.
javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.
This runs the Java interpreter. You should then see your program output.
If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!
To complete the answer :
Compile the Java File to a *.class file
- This will create a TheJavaFile.class file
Execution of the Java File
Creation of an executable *.jar file
You’ve got two options here —
With an external manifest file :
Create the manifest file say — MANIFEST.mf
The MANIFEST file is nothing but an explicit entry of the Main Class
jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class
Executable by Entry Point:
To run the Jar File
In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs , then you need to run it with the package name.
Compile it in the usual way:
But to run it, you need to give the package name and then your java class name:
Complile a Java file to generate a class:
Execute the generated class:
Assuming the file is called «CopyFile.java», do the following:
The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.
This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330
For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html
It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.
Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.
Then you can compile your file using command
Then run it using
So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.
You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they’re in the same directory
If you’re having an issue resulting with «could not find or load main class» you may not have jre in your path. Have a look at this question: Could not find or load main class
On Windows 7 I had to do the following:
quick way
- Install JDK http://www.oracle.com/technetwork/java/javase/downloads
- in windows, browse into «C:\Program Files\Java\jdk1.8.0_91\bin» (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do «open command window here» and this will give you a command line and access to all the BIN tools. «javac» is not by default in the windows system PATH environment variable.
- Follow comments above about how to compile the file («javac MyFile.java» then «java MyFile») https://stackoverflow.com/a/33149828/194872
long way
- Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
- After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but «javac» is NOT one of them so when trying to run «javac» from Windows command line it throws an error.
- I edited the path: Control Panel -> System -> Advanced tab -> «Environment Variables. » button -> scroll down to «Path», highlight and edit -> replaced the «C:\ProgramData\Oracle\Java\javapath» with a direct path to the java BIN folder «C:\Program Files\Java\jdk1.8.0_91\bin».
This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.