Java program windows cmd

Java program 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.

  • Select Options -> Edit Options -> Insert Mode. Start in to «C:\introcs» or whichever directory you’d like to start in when launching the Command Prompt. —>
  • 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.

    How to run a java program by cmd — Stack Overflow

    How to compile java programs through windows cmd

    Posted August 28, 2021 by Chris Luongo in Java programming , Windows

    Although many people compile Java programs within the IDE, the Windows command line terminal is a powerful compiling option.

    When starting out with Java, many users get confused about compiling the code. Frequently, a programing IDE adds additional layers of confusion and complexity that complicates debugging and learning. Learning how to compile directly from within the Windows shell is an essential skill to master. These steps will walk you through installing the Java SDK and compiling your code from within the Windows terminal. These commands are case-sensitive.

    In this screencast I walkthrough the required steps. Refer to the text and images below for more specific details.

    1. First things first, you need to download the JDK from Oracle to have the latest version of Java.

    2. Follow the instructions to install the JDK. It is important to make note of the path of the JDK install.

    3. Create a central directory to hold all your Java files. For example, I created a folder at C:java and placed my .java files and projects within this folder.

    4. Click the Windows Start icon and search for System and hit enter. Select Advanced system settings on the left and then select Environment Variables .

    5. Under System variables scroll down to the variable Path .

    6. Hit Edit at the beginning of the Variable value . We need to place the path of the Java compiler into Windows’s path. The compiler should be located in the JDK bin folder. For example, from the install I recorded that my bin folder was at the following location: C:Program Files (x86)Javajdk1.7.0_06bin; but your location may be different. Be sure to include a semi-colon at the end of the string you just added. Hit OK and close this.

    If this is done incorrectly, you will get the following error when attempting to compile:

    ‘javac’ is not recognized as an internal or external command, operable program or batch file

    7. Next, we need to open a terminal window or CMD shell. Click the Windows icon and search for “CMD” then hit enter. Change to the directory of your personal java files. For example, I would input cd java since that is the personal java folder I created above. Now our current directory within the CMD shell is c:java .

    8. Type in javac JavaFileName.java where the “JavaFileName.java” is the name of the java file you want to compile. This file can be created with any text editor or IDE and contains your actual code. After hitting the enter key, you should see a new blank line in the CMD with nothing in it Now check within your personal Java folder. If the compile was successful, you should see a new .class file.

    9. To actually run the interpreter and see output type in java YourFileName without the .java extension and your program should execute. My example simply outputs some text.

    How to run a java program by cmd

    I finished my little app. so now i would like to see the result by command prompt. (in eclipse works well).

    first step i decided (to be sure) to compile by command prompt my program:

    i compiled without error in fact i have my files .class (all the program have just 1 class but i have some inner class and so i have more than 1 file .class)

    now if i try to run my program:

    i have this problem on the prompt:

    but i don’t understand why… and what i have to do…

    this is my code:
    >

    Java source и каталоги классов

    Простой Java-проект содержит один каталог, внутри которого хранятся все исходные файлы. Файлы обычно хранятся не внутри исходного каталога, а в подкаталогах, соответствующих их структуре пакета. Пакеты — это просто способ сгруппировать исходные файлы, которые принадлежат друг другу. Исходный каталог часто называют src, но это не является обязательным требованием.

    Например, если вы используете инструмент сборки Maven, вы, как правило, будете использовать другую структуру каталогов, где исходный код Java хранится в каталоге src/main/java(в корневом каталоге вашего проекта).

    Когда вы компилируете весь исходный код в Java, компилятор создает один файл .class для каждого файла .java. .Class содержит скомпилированную версию файла .java. Байт-код для файла .java, другими словами.

    Это файлы .class, которые может выполнять виртуальная машина. Не файлы .java. Поэтому нормально отделять файлы .java от файлов .class. Обычно это делается путем указания компилятору записать файлы .class в отдельный каталог.

    Этот каталог часто называют классами, но, опять же, он не является обязательным, и он зависит от того, какой инструмент сборки используете, IDE и т. д.

    Выполнение скомпилированного кода

    После того, как компилятор выполнит свою работу, каталог classes будет содержать скомпилированные файлы .class. Структура пакета(структура каталогов) из исходного каталога будет сохранена в каталоге классов.

    Вы можете запустить любой из этих файлов .class, в котором есть метод main(). Вы можете запустить .class изнутри вашей Java IDE или из командной строки. Запуск из командной строки это выглядит так:

    Флаг -cp сообщает виртуальной машине, что все ваши классы находятся в каталоге, называемом классы. Это также называется «путь к классу»(отсюда сокращение cp).

    Имя класса для запуска является последним аргументом в приведенной выше команде — часть myfirstapp.MyJavaApp. JVM должна знать полное имя класса(все пакеты плюс имя класса), чтобы определить, где находится соответствующий файл .class.

    Когда вы запустите класс, ваша командная строка будет выглядеть примерно так(включая вывод из приложения):

    Обратите внимание, что в первой команде не должно быть разрыва строки. Я добавил это только для того, чтобы было легче читать.

    Как выполнять команды cmd через java

    каждое исполнение exec порождает новый процесс со своей собственной средой. Таким образом, ваш второй вызов никак не связан с первым. Это просто изменится своя рабочий каталог, а затем выход (т. е. это фактически no-op).

    Если вы хотите составлять запросы, вам нужно будет сделать это в течение одного вызова exec . Bash позволяет указывать несколько команд в одной строке, если они разделены точками с запятой; Windows CMD может разрешить то же самое, и если нет, всегда есть пакетные сценарии.

    как говорит Петр , если этот пример на самом деле чего вы пытаетесь достигнуть, вы можете выполнить такую же вещь очень более эффективно, эффектно и платформу-безопасно с следующим:

    Как компилировать и запускать программу java с помощью командной строки

    wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали, в том числе анонимно, 22 человек(а).

    Количество просмотров этой статьи: 47 316.

    Компиляция исходного кода java

    Вы можете скомпилировать исходный код Java непосредственно из вашей IDE(если вы используете IDE). Или вы можете использовать компилятор, который поставляется вместе с Java SDK. Чтобы выполнить компиляцию java кода из командной строки, сделайте следующее:

    • Откройте командную строку (cmd)
    • Перейдите в корневой каталог вашего проекта(не в исходный каталог)
    • Убедитесь, что корневой каталог проекта содержит исходный каталог и каталог классов
    • Введите команду ниже(в Windows — другие ОС будут выглядеть аналогично):

    Эта команда выполняет javac(компилятор), которая скомпилирует код в каталоге src / myfirstapp. * . А даже точнее все файлы в данном каталоге.

    Каталог myfirstapp — это пакет в корневом каталоге исходного кода src. Если у вас есть несколько пакетов в корневом каталоге, вам придется запускать компилятор несколько раз. Java IDE обрабатывает это автоматически. Так же как и инструменты для сборки, такие как Ant, Maven или Gradle.

    Читайте также:  Windows gpedit msc download
    Оцените статью