[英]Create File From User Input
I need to prompt the user for input and create a new file based on their input. 我需要提示用户输入并根据他们的输入创建一个新文件。 For example, if a user entered data
then data.txt
should be a newly created file. 例如,如果用户输入了data
则data.txt
应该是一个新创建的文件。 I have my code written to take the name of the file, but how do I actually create the file? 我已编写代码以使用文件名,但是如何真正创建文件? Any ideas are appreciated, thanks! 任何想法表示赞赏,谢谢!
System.out.print("Please enter an output file: ");
Scanner k = new Scanner(System.in);
String fileName = k.nextLine();
str = fileName + ".txt";
try{
File userFile = new File("?")
}
Once you create the File object using File userFile = new File(fileName)
, you can make sure the file exists by calling userFile.createNewFile()
. 使用File userFile = new File(fileName)
创建File对象后,可以通过调用userFile.createNewFile()
来确保文件存在。 This function will only create the file if it does not exist. 如果该文件不存在,则此函数只会创建该文件。 If it does exists it will just use that file. 如果确实存在,它将仅使用该文件。 If you care to check whether a file of that name already exists, the userFile.createNewFile()
function will return true if it creates it, false if it already exists. 如果您要检查是否已经存在该名称的文件,则userFile.createNewFile()
函数创建后将返回true,如果已经存在则返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.