Java console program jar

Java console application

Java console application tutorial shows how to create a Java console application. The application computes some statistics.

2.3, 3.5, 5, 6.7, 3.2, 1.2, 6.7, 7.8 4.5, 2.1, 6.6, 8.7, 3.2, 1.0, 1.2, 3

Somewhere on the disk we have this file. The file name will be a console parameter to our program.

$ tree . ├── nbactions.xml ├── pom.xml └── src ├── main │ └── java │ └── com │ └── zetcode │ ├── JavaStatsEx.java │ └── MyStatsApp.java └── test └── java

This is the project structure.

  4.0.0 com.zetcode JavaConsoleApp 1.0-SNAPSHOT jar UTF-8 1.8 1.8   commons-cli commons-cli 1.4  com.opencsv opencsv 4.1  org.apache.commons commons-math3 3.6.1  org.apache.commons commons-lang3 3.7     org.codehaus.mojo exec-maven-plugin 1.5.0 com.zetcode.JavaStatsEx false -f /home/janbodnar/tmp/data.csv       

In the pom.xml file, we define the dependencies of the application. The commons-cli artifact is for parsing command line arguments, opencsv for reading CSV data, commons-math for statistical calculations, and commons-lang3 for transforming list into an array.

The exec-maven-plugin executes Java programs from Maven. In the arguments tag, we give the application the option and the filename.

package com.zetcode; /** * Starter class for MyStats application. * * @author janbodnar */ public class JavaStatsEx < /** * Application entry point. * * @param args application command line arguments */ public static void main(String[] args) < MyStatsApp msp = new MyStatsApp(); msp.run(args); >>

JavaStatsEx is the application entry point. It creates the instance of MyStatsApp and passes it the application arguments.

package com.zetcode; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.math3.stat.StatUtils; /** * MyStatsApp is a simple console application which computes * basic statistics of a series of data values. The application takes * a file of data as its single argument. * * @author janbodnar */ public class MyStatsApp < /** * Runs the application * * @param args an array of String arguments to be parsed */ public void run(String[] args) < CommandLine line = parseArguments(args); if (line.hasOption("filename")) < System.out.println(line.getOptionValue("filename")); String fileName = line.getOptionValue("filename"); double[] data = readData(fileName); calculateAndPrintStats(data); >else < printAppHelp(); >> /** * Parses application arguments * * @param args * @return CommandLine which represents a list of application * arguments. */ private CommandLine parseArguments(String[] args) < Options options = getOptions(); CommandLine line = null; CommandLineParser parser = new DefaultParser(); try < line = parser.parse(options, args); >catch (ParseException ex) < System.err.println(ex); printAppHelp(); System.exit(1); >return line; > /** * Reads application data from a file * * @param fileName * @return array of double values */ private double[] readData(String fileName) < Listdata = new ArrayList(); double[] mydata = null; try (Reader reader = Files.newBufferedReader(Paths.get(fileName)); CSVReader csvReader = new CSVReaderBuilder(reader).build()) < String[] nextLine; while ((nextLine = csvReader.readNext()) != null) < for (String e : nextLine) < data.add(Double.parseDouble(e)); >> mydata = ArrayUtils.toPrimitive(data.toArray(new Double[data.size()])); > catch (IOException ex) < System.err.println(ex); System.exit(1); >return mydata; > /** * Generates application command line options * * @return application Options */ private Options getOptions() < Options options = new Options(); options.addOption("f", "filename", true, "file name to load data from"); return options; >/** * Prints application help */ private void printAppHelp() < Options options = getOptions(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JavaStatsEx", options, true); >/** * Calculates and prints data statistics * * @param data input data */ private void calculateAndPrintStats(double[] data) < System.out.format("Geometric mean: %f%n", StatUtils.geometricMean(data)); System.out.format("Arithmetic mean: %f%n", StatUtils.mean(data)); System.out.format("Max: %f%n", StatUtils.max(data)); System.out.format("Min: %f%n", StatUtils.min(data)); System.out.format("Sum: %f%n", StatUtils.sum(data)); System.out.format("Variance: %f%n", StatUtils.variance(data)); >>
CommandLine line = parseArguments(args);

The parseArguments method parses the command line arguments. It returns CommandLine , which represents a list of arguments parsed against a Options descriptor.

Читайте также:  Python массивы все команды

if (line.hasOption(«filename»)) < System.out.println(line.getOptionValue("filename")); String fileName = line.getOptionValue("filename"); double[] data = readData(fileName); calculateAndPrintStats(data); >else

The application has a mandatory filename option, which points to the file to be read and compute statistics from. If it is not present, we provide the application help message.

Options options = getOptions();

The getOptions method returns the options of the application.

CommandLineParser parser = new DefaultParser(); try < line = parser.parse(options, args); >catch (ParseException ex) < System.err.println(ex); printAppHelp(); System.exit(1); >return line;

CommandLineParser parses the command line arguments. The application exits if there is a ParseException . The parser returns parsed arguments in CommandLine object.

try (Reader reader = Files.newBufferedReader(Paths.get(fileName)); CSVReader csvReader = new CSVReaderBuilder(reader).build()) 

CSVReader is used to read CSV data.

String[] nextLine; while ((nextLine = csvReader.readNext()) != null) < for (String e : nextLine) < data.add(Double.parseDouble(e)); >>

In this while loop, we read the CSV file line by line and parse the data into a list of Double values.

mydata = ArrayUtils.toPrimitive(data.toArray(new Double[data.size()]));

We need primitive data types to calculate the statistics; therefore, we transform the list into an array of primitive double values. ArrayUtils comes from the Apache Commons Lang library.

private Options getOptions()

The getOptions provides the application options.

private void printAppHelp()

The printAppHelp prints the help of the application. It uses HelpFormatter to do the job.

private void calculateAndPrintStats(double[] data)

With StatUtils , we compute some statistics. The StatUtils takes a Java array as a parameter.

$ mvn -q exec:java /home/janbodnar/tmp/data.csv Geometric mean: 3.412562 Arithmetic mean: 4.168750 Max: 8.700000 Min: 1.000000 Sum: 66.700000 Variance: 6.158292

In this tutorial, we have created a simple Java console application, which computes basic statistics from a CSV file.

Источник

Как написать простое консольное приложение с аргументами на Java

В данном посте я хочу рассказать , как создать простое консольное приложение на Java с использованием библиотеки args4j.

Не давно мне дали задание написать консольную утилиту при помощи библиотеки для парсинга аргументов. Я выбрал args4j и хочу поделиться своим опытом.

Разработать консольную утилиту, которая соединяет заданные в командной строке входные текстовые файлы в выходной, указываемый после ключа -out. С ключом -u делает обратную операцию, принимая один входной файл и разбивая его на несколько. Выходной файл тоже является текстовым. Придумать для него формат, позволяющий запоминать имена входных файлов и находить их границы. Command Line: tar -u filename.txt или tar file1.txt file2.txt … -out output.txt.

Сначала надо подключить зависимость, я использовал Maven. Тут все простенько:

Теперь можно реализовать парсинг аргументов. Создадим класс Parser и добавим туда две переменные и список для остальных аргументов.

Аннотация сверху дает понять библиотеке args4j, где хранить аргументы , значения опций и всякое , в общем все прям для ленивых. Сейчас будет чуть сложнее, нужно осмыслить то , что получили из консоли:

public static void main(String[] args) < new Parser().run(args); >private void run(String[] args) < CmdLineParser parser = new CmdLineParser(this); try < parser.parseArgument(args); if ((arguments == null && out != null) || (u != null && out != null)) < System.err.println("Ошибка ввода аргументов!"); System.err.println("tar [опции. ] аргументы. "); System.err.println("\nПример: tar -u \"filename.txt\" \n tar \"file1.txt file2.txt\" -out output.txt"); throw new IllegalArgumentException(""); >if (out != null) < new Delimiter().tar(arguments.split(" "), out); >else < if((u!=null && !Objects.requireNonNull(u).exists()) )< throw new IOException("Папки или файла не существует"); >new Delimiter().tar(u); > > catch (CmdLineException | IOException e) < System.err.println(e.getMessage()); System.exit(1); >>

В данном кусочке в основном можно обойтись самой популярной комбинацией клавиш у программистов , но я все же попробую часть разжевать. В начале стоит понимать , что мои проверки могут вам не подойти (9 строчку скорее всего придется переделать) там просто проверяю правильно ли пользователь ввел аргументы и если да , то смотрю , что дальше с ними делать. Если опция -out активирована, то идем в эту часть кода:

public void tar(String[] arguments, String out) throws IOException, CmdLineException < File f = new File(out); FileWriter writer; StringBuilder builder; if (f.createNewFile()) < writer = new FileWriter(f); for (String argument : arguments) < if(new File(argument).exists()) < FileReader fr = new FileReader(argument); BufferedReader reader = new BufferedReader(fr); builder = new StringBuilder(); int countLines = 0; String temp; while ((temp = reader.readLine()) != null) < builder.append(temp).append("\n"); countLines++; >writer.write(argument + " " + countLines + "\n"); writer.write(builder.toString()); >else < System.out.println("Неверный аргумент "+ argument + "\n пример: \"text1.txt text2.txt\" -out text3.txt"); >> writer.close(); > else < throw new IOException("Не возможно создать новый файл"); >>

Предварительно создал новый класс Delimiter и написал две простенькие функции. Не думаю , что кому-то это сильно пригодится , да и тут в принципе не сложно , так что рассказывать не буду. Второй метод (просто перегрузил метод tar) :

public void tar(File u) throws IOException < FileReader fr = new FileReader(u); BufferedReader reader = new BufferedReader(fr); String buf = reader.readLine(); FileWriter writer; if(buf.matches("([A-Za-z0-9-_.]+/?)+ 2+")) < while (buf != null) < String[] data = buf.trim().split(" "); String name = data[0]; int size = Integer.parseInt(data[1]); File f = new File(name); if (f.createNewFile()) < StringBuilder builder = new StringBuilder(); writer = new FileWriter(f); for (int i = 0; i < size; i++) < builder.append(reader.readLine()).append("\n"); >writer.write(builder.toString()); writer.close(); > else < System.out.println("Файл уже существует"); >buf = reader.readLine(); > >else < reader.close(); throw new IOException("Неверные данные , нужен другой файл!"); >reader.close(); >

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

Осталось самое главное

Нужно как-то собрать jar файл , чтобы запускать его из консоли. Есть два пути , один сложный и правильный , второй простой , но он не имеет ничего общего с хорошей программой. Для первого способа нужно прописывать все зависимости в manifest , но я пока для этого способа сыроват , есть второй - с помощью плагина:

--> org.apache.maven.plugins maven-assembly-plugin 3.5.0   org.apache.maven.plugins maven-assembly-plugin 3.5.0   org.spbstu.gorchatovra.Parser   jar-with-dependencies    assemble-all package single    

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

Вот и подошел к концу пост , надеюсь кому-то смог помочь, я программист мягко говоря начинающий , так что я открыт для предложений , готовый проект тут.

Источник

Console input and output in Java - How to generate executable jar

Often, programs need to communicate with a user. Users are the people who interact with programs.

This communication has two directions; input and output:

  • Input: The user gives the program information.
  • Output: The program provides information to the user.

Let's see how to do this in a command line application.

Console Output

An easy way to create a new class with Eclipse is right-click on src - New - Class

Salida por la consola

Name the class with "ConsoleOutput" and select the main method. Click finish.

Remove the TODO comment in the main method and write "syso", then press the Ctrl key+the space bar. If everything went well, "syso" became "System.out.println ()". Ctrl-space gives help on many occasions.

package com.edu4java.javatutorials; public class ConsoleOutput < public static void main(String[] args) < System.out.println("Hello World"); >>

The above code prints Hello World to the console. Right-click on the class - Run As - Java Application and we will be able to see "Hello World" in Console View.

Console Input

Just as we print on the console, you can also enter data through the console.

Create a class called ConsoleInput with a main method in the same way as before. Replace the comment with the following code;

InputStream stream = System.in; Scanner scanner = new Scanner(stream); System.out.println("Name:"); String input = scanner.next(); System.out.println("Hello " + input); scanner.close();

We will see errors marked in red because there are missing imports:

import java.io.InputStream; import java.util.Scanner;

If we press Ctrl + Shift and the letter "o", imports will be added automatically. If Eclipse has access to more than one class with the same name, it will give you the option to choose the package for import.

Code explanation

InputStream stream = System.in;

In the first line we store in a variable called stream, an object maintained by Java. This variable belongs to the class in of the System class.

This InputStream object, is like a stream of data coming from the keyboard.

Scanner scanner = new Scanner(stream);

In the second line we create a Scanner object, using as parameter a data stream. This is possible because Scanner has a constructor that accepts InputStream objects.

Prints "Name" on the console.

String input = scanner.next();

This sentence locks the execution, waiting for a data input ended with a return key. The next () function, returns the string entered before the return key.

System.out.println("Hello " + input);

Prints "Hello", followed by anything we insert through the console.

The Scanner object has a close () method to be informed when they are no longer needed. Normally, close () methods are used internally to release resources held by the object.

We can test the class right-clicking on the class; - Run As - Java Application. Click on the console to gain focus and write a name and click on the return key.

Create an executable jar with Eclipse

To test the MS-DOS console, we will generate a jar file that runs the ConsoleInput class. It is important to run before Run As - Java Application so that a launch configuration is created.

Right-click on the project - export - Java - Runnable JAR File

Exportar a archivo JAR ejecutable

In Launch configuration choose the class ConsoleInput. In Export destination choose where you want to place the jar file and click Finish.

To open a new MS-DOS window with cmd.exe, navigate to the directory where the jar file is and run it with java -jar console.jar

Entrada por la consola en Java

Main method arguments

Finally, let's create a class to test the parameters received by the main method. String [] args is a String array, where we locate the arguments added when we run a java class. In our example, the argument will be the name of the user, which will be stored in the first position of the array args [0] .

package com.edu4java.javatutorials; public class ConsoleParameters < public static void main(String[] args) < System.out.println("Hello "+args[0]); >>

We run the program with right-click on the class - Run As - Java Application and on the console we will see:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.edu4java.javatutorials.ConsoleParameters.main(ConsoleParameters.java:6)

We get an error because it it is trying to get to the first position of the array and Eclipse didn´t send any arguments.

Let's create the executable jar for ConsoleParameters. Do not forget to choose the class ConsoleParameters in the launch configuration. Execute java -jar console.jar edup. This sends edup as an argument that will be received as parameter in the first position of args. If everything is ok, the result should be:

Источник

Оцените статью