0

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?

Martin
  • 17
  • 2

2 Answers2

0

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.

Eric
  • 36
  • 3
  • How to use the args[0] and args[1]? – Martin Aug 18 '22 at 12:42
  • In java, `args[0], args[0], ... ` is the command line arguments. Support your java run command is `java FileIo filename.txt anotherFileName.txt`, then the args[0] is 'filename.txt', and args[1] is 'anotherFileName.txt'. In IDE like IDEA, args is defined in the Run/Debug Configurations->Program arguments (see ) – Eric Aug 19 '22 at 08:10
-2

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

Hi computer
  • 946
  • 4
  • 8
  • 19
  • 3
    As of Java 9 there is indeed a [Java REPL](https://docs.oracle.com/javase/9/jshell/introduction-jshell.htm), although I can't see anything in the question that relies on one. – jsheeran Aug 18 '22 at 09:28
  • 1. isn't true these days. In later JDKs. `jshell` is REPL tool and with certain source files you can use java launcher direct from source file: `java xyz.java` – DuncG Aug 18 '22 at 09:29
  • sorry about that, I should look more into it – Hi computer Aug 18 '22 at 09:52