简体   繁体   English

如何基于Java中的用户输入创建新的文本文件?

[英]How to create a new text file based on the user input in Java?

I'm trying to create a new text file in java by having the user input their desired file name. 我正在尝试通过让用户输入所需的文件名来在Java中创建一个新的文本文件。 However, when I look in the directory for the file after I run the code once, it doesn't show up. 但是,当我运行一次代码后在目录中查找文件时,它不会显示。

import java.util.Scanner;
import java.io.File;

public class TestFile {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the desired name of your file: ");
        String fileName = input.nextLine();
        fileName = fileName + ".txt";

        File file = new File(fileName);
    }
}

Although, when I don't have the user input a file name and just have the code written with the name in quotation marks, the file ends up being created when I look back in the directory. 虽然,当我没有用户输入文件名而只用双引号将代码写成代码时,当我回头查看目录时,文件最终被创建了。

File file = new File("TestFile.txt")

Why won't it create a file when I try to use the String input from the user? 当我尝试使用用户输入的String时,为什么不创建文件?

You must be mistaken because just calling new File(String) won't create a file. 您一定会误会,因为仅调用new File(String)不会创建文件。 It will just create an instance of File class. 它将仅创建File类的实例。

You need to call file.createNewFile() . 您需要调用file.createNewFile()

Adding this at the end creates the file:- 在末尾添加此文件将创建文件:

if (file.createNewFile()) {
    System.out.println("File created.");
} else {
    System.out.println("File already exists.");
}

The following code worked for me: 以下代码为我工作:

    Scanner input = new Scanner(System.in);
    System.out.print("Enter the desired name of your file: ");
    String fileName = input.nextLine();
    fileName = fileName + ".txt";

    File file = new File(fileName);
    boolean isFileCreated = file.createNewFile();  // New change
    System.out.print("Was the file created? -- ");
    System.out.println(isFileCreated);

The only change made to your code is to call createNewFile method. 对您的代码所做的唯一更改是调用createNewFile方法。 This worked fine in all cases. 在所有情况下都可以正常工作。 Hope this helps. 希望这可以帮助。

From the API: 从API:

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. 当且仅当具有该抽象路径名的文件尚不存在时,以原子方式创建一个新的空文件。 The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. 检查文件是否存在以及是否创建文件(如果文件不存在)是单个操作,对于可能影响文件的所有其他文件系统活动而言,这是原子操作。 Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. 注意:此方法不应用于文件锁定,因为不能使生成的协议可靠地工作。 The FileLock facility should be used instead. 应该改用FileLock工具。

Please use below code to solve your issue. 请使用以下代码解决您的问题。 You just have to call createNewFile() method it will create file in your project location. 您只需要调用createNewFile()方法即可在您的项目位置创建文件。 You can also provide the location where you want to create file otherwise it will create file at your project location to create file at specified location you have to provide location of your system like below 您还可以提供要创建文件的位置,否则它将在您的项目位置创建文件以在指定位置创建文件,您必须提供系统位置,如下所示

String fileLocation="fileLocation"+fileName;
File file = new File(fileLocation);


import java.util.Scanner;
import java.io.File;

public class TestFile {
public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the desired name of your file: ");
        String fileName = input.nextLine();
        fileName = fileName + ".txt";

        File file = new File(fileName);
        file.createNewFile();
    }
}

When faced with issues like this, it's really, really, really important to go hit the JavaDocs , because 90% of the time, it's just a misunderstanding of how the APIs work. 当遇到这样的问题时,使用JavaDoc非常重要,因为90%的时间都是对API的工作方式的误解。

File is described as: File描述为:

An abstract representation of file and directory pathnames. 文件和目录路径名的抽象表示。

This means that creating an instance of File does not create a file nor does the file have to exist, it's just away of describing a virtual concept of a file. 这意味着创建File的实例不会创建文件,也不必存在文件,这只是描述文件的虚拟概念而已。

Further reading of the docs would have lead you to File#createNewFile which is described as doing: 对文档的进一步阅读将带您进入File#createNewFile ,它被描述为:

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. 当且仅当具有该抽象路径名的文件尚不存在时,以原子方式创建一个新的空文件。 The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. 检查文件是否存在以及是否创建文件(如果文件不存在)是单个操作,对于可能影响文件的所有其他文件系统活动而言,这是原子操作。

When you initialize your File file = new File("TestFile.txt") , it is not created yet. 当您初始化File file = new File("TestFile.txt") ,尚未创建。 You should write something to your file using FileWriter or others. 您应该使用FileWriter或其他工具向文件中写入内容。

File f = new File(fileName);
FileWriter w = new FileWriter(f);
w.write("aaa");
w.flush();

or using f.createNewFile() as suggested in other answer. 或使用其他答案中建议的f.createNewFile() Then you can see your file and its content. 然后,您可以查看文件及其内容。

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

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