Home > Mobile >  How to read and write files from the command line in Java?
How to read and write files from the command line in Java?

Time:08-18

I have that code in Python, but I want to do the same thing in Java.

import sys

def main(args):
    # Showing the arguments of the program
    print("#ARGS = %i" %len((args)))
    print("PROGRAM = %s" %(args[0]))
    print("ARG1 = %s, ARG2 = %s" %(args[1], args[2]))
    # Open files
    input = open(sys.argv[1],'r')
    output = open(sys.argv[2],'w')
    # ...
    # Closing files
    input.close()
    output.close()
    # end of the program

if __name__ == '__main__':
    main(sys.argv)

The same code in C

#include <stdio.h>

int main(int argc, char* argv[]) {
    // Showing the arguments of the program
    printf("#ARGS = %i\n", argc);
    printf("PROGRAMA = %s\n", argv[0]);
    printf("ARG1 = %s, ARG2 = %s\n", argv[1], argv[2]);
    // Opening files
    FILE* input = fopen(argv[1], "r");
    FILE* output = fopen(argv[2], "w");
    // ...
    // Closing files
    fclose(input);
    fclose(output);
    // End of the program
    return 0;
}

How can I create a code like that in Java? Is there a command like that "input = open(sys.argv[1],'r')" or "FILE* input = fopen(argv[1], "r")" in Java?

CodePudding user response:

We can use Scanner to read from file, and use PrintWriter to write to a file.

public class FileIo {
    public static void main(String[] args) throws FileNotFoundException {
        try (
                Scanner in = new Scanner(new File("filename.txt"));
                PrintWriter out = new PrintWriter("anotherFileName.txt")
        ) {

            while (in.hasNextLine()) {
                String str = in.nextLine();
                out.println(str);
            }
        }
    }
}

In java, the try(resources) {} block will automatically close its resources.

Use args[0] and args[1] to replace the in and out file name.

CodePudding user response:

java 9 or above

java provide repl env what is repl jshell since java version 9

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> Math.round(34.543)
$1 ==> 35

read/write file with FileReader/FileWriter example

jshell> import java.io.*;

jshell> BufferedWriter writer = new BufferedWriter(new FileWriter("/Users/xxx/local/tempFiles/gids", true));
   ...> writer.write("appended text");
   ...> writer.close();
   ...>
writer ==> java.io.BufferedWriter@66a29884

jshell>

jshell> BufferedReader reader = new BufferedReader(new FileReader("/Users/xxx/local/tempFiles/gids"));
   ...> String currentLine = reader.readLine();
   ...> reader.close();
   ...>
reader ==> java.io.BufferedReader@17a7cec2
currentLine ==> "appended textappended text"

jshell> currentLine
currentLine ==> "appended textappended text"

jshell>

java 8

  1. put a while(true) loop in main method, and get user input, and process things accordingly. For example, q for exit, r /User/xxx/file for read file '/User/xxx/file', and it is not great because you have to consider all the requirements and needs and it is set, you can not change the code at runtime.

  2. groovysh, you can run java code in it

  •  Tags:  
  • java
  • Related