[英]I can't manipulate name of the file that filewriter class creates
I am working on a simple program that takes input from user and then saves it with specific file name.我正在开发一个简单的程序,它从用户那里获取输入,然后用特定的文件名保存它。
To be more precise:更准确地说:
public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;
public static void main(String[] args) throws IOException {
System.out.print("File name: ");
name = in.nextLine();
fw = new FileWriter(name + ".txt", false);
System.out.println("Continue typing/type save to quit");
while(!quit) {
String word = in.nextLine();
if(word.equals("save")) {
fw.close();
quit = true;
}
else {
fw.write(word + "\n");
}
}
As you can see program ask user for file name at the beginning, before he starts to type.正如您所看到的,程序在开始输入之前询问用户文件名。 This is my problem.
这是我的问题。 I want my program to ask the user for a file name at the end, after he typed all words.
我希望我的程序在用户输入所有单词后,在最后询问用户一个文件名。 Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.
不幸的是,我不能这样做,因为 filewriter 类在创建新对象时创建文件,并且以后不能更改名称。
I would like to know is there any solution to my problem or what kind of information should I look for.我想知道是否有任何解决方案可以解决我的问题,或者我应该寻找什么样的信息。
You have two options:您有两个选择:
List<String>
for instance) and then write out the words after seeing the save
keyword and getting the output filename from the user.List<String>
中),然后在看到save
关键字并从用户获取输出文件名后写出单词。save
keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.save
关键字,关闭文件,获取用户选择的文件名,然后将临时文件重命名为用户选择的文件名。 Unless you need to process millions of words I'd go with option 1 for its simplicity.除非您需要处理数百万个单词,否则为了简单起见,我会选择选项 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.