[英]How to read and write files from the command line 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)
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;
}
如何在 Java 中创建这样的代码? Java 中是否有类似“input = open(sys.argv[1],'r')”或“FILE* input = fopen(argv[1],“r”)”的命令?
我们可以使用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);
}
}
}
}
在 java 中, try(resources) {}
块将自动关闭其资源。
使用args[0]
和args[1]
替换 in 和 out 文件名。
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
使用 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>
在 main 方法中放置一个while(true)
循环,并获取用户输入,并相应地处理事情。 例如, q
表示退出, r /User/xxx/file
用于读取文件'/User/xxx/file',这不是很好,因为您必须考虑所有要求和需要并且已设置,您无法更改运行时的代码。
groovysh ,您可以在其中运行 java 代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.