如何将文件名作为参数传递,创建然后读取文件

How to pass a file name as parameter, create and then read the file

我有一个方法如下:

    public(String input_filename, String output_filename)
   {
//some content
    }

如何在 运行 时创建 input_filename 并读取 input_filename 。我必须将 input_filename 作为参数传递

我是新手,请耐心等待Java

我不确定你想用这种方法做什么,但我希望这能对你有所帮助。 如果要在运行时输入,请使用 Scanner class。 A guide on how to use it here

此外,如果您想要在 class 中输出,您应该使用 "return",而不是将其作为参数。

请注意,您尚未命名 class,或指定输出类型。

它的外观:

public String className(String input){
    return input;
}

这里是一个完整的示例:

另存为Sample.java

编译它:javac Sample.java

运行 它与:java Sample "in.txt" "out.txt"

或:java Sample

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Sample {
    public static void main(String[] args) throws IOException {
        if(args.length == 2)
        {
            doFileStuff(args[0],args[1]);
        }
        else {
            doFileStuff("in.txt","out.txt");
        }
    }

    public static void doFileStuff(String input_filename, String output_filename) throws IOException {

        if(!Files.exists(Paths.get(input_filename)))
        {
            System.err.println("file not exist: " + input_filename);
            return;
        }

        if(!Files.exists(Paths.get(output_filename)))
        {
            System.err.println("file still exist, do not overwrite it: " + output_filename);
            return;
        }

        String content = new String(Files.readAllBytes(Paths.get(input_filename)));

        content += "\nHas added something";

        Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
    }
}