简体   繁体   English

Java中的命令行如何读写文件?

[英]How to read and write files from the command line in Java?

I have that code in Python, but I want to do the same thing in Java.我在 Python 中有该代码,但我想在 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 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?如何在 Java 中创建这样的代码? Is there a command like that "input = open(sys.argv[1],'r')" or "FILE* input = fopen(argv[1], "r")" in Java? Java 中是否有类似“input = open(sys.argv[1],'r')”或“FILE* input = fopen(argv[1],“r”)”的命令?

We can use Scanner to read from file, and use PrintWriter to write to a file.我们可以使用Scanner读取文件,并使用PrintWriter写入文件。

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.在 java 中, try(resources) {}块将自动关闭其资源。

Use args[0] and args[1] to replace the in and out file name.使用args[0]args[1]替换 in 和 out 文件名。

java 9 or above java 9以上

java provide repl env what is repl jshell since java version 9 java 提供 repl env 什么是 repl jshell自 java 版本 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使用 FileReader/FileWriter 示例读取/写入文件

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 java 8

  1. put a while(true) loop in main method, and get user input, and process things accordingly.在 main 方法中放置一个while(true)循环,并获取用户输入,并相应地处理事情。 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.例如, q表示退出, r /User/xxx/file用于读取文件'/User/xxx/file',这不是很好,因为您必须考虑所有要求和需要并且已设置,您无法更改运行时的代码。

  2. groovysh , you can run java code in it groovysh ,您可以在其中运行 java 代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM