JavaFx将数据保存到txt文件 - 检查文件是否存在

时间:2016-02-28 10:59:31

标签: java text

我正在建立一个将数据保存到txt的系统。

1 - 我已宣布该文件:

public static final File file = new File("src/window/data.txt");

2 - 无效的系统

    public void checkData() throws Exception
{

    Scanner scan = new Scanner(file);
    if (scan.hasNext() == false)
    {
        System.out.println("file is empty");
        BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
        fileWriter.write("test");

    }
    else
    {

        System.out.println("file is not empty");

    }

}

它离开返回false表示打印"文件为空"

2 个答案:

答案 0 :(得分:1)

我已使用try-catch语句对该代码进行了编辑,并尝试使用包含任何数据的"data.txt"并运行:

public static final File file = new File("data.txt");

public static void main(String[] args) {
    try (Scanner scan = new Scanner(file)) {
        if (!scan.hasNext()) {
            System.out.println("file is empty");
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
            fileWriter.write("test");  
        } else {
            System.out.println("file is not empty");
        }   
    } catch  (IOException ex) {
        System.out.println(ex);
    }
}

输出为"file is not empty"。请尝试我的代码并检查文件的路径是否正确。

答案 1 :(得分:0)

您可以使用Java的更新功能,例如: G。 PathPathsFiles,以便编写文本文件并检查文件是否存在和空白。

public static void writeFile(String filePath, List<String> lines) {

    try {

        Path path = Paths.get(filePath);
        boolean exists = Files.exists(path);

        System.out.println( "File " + path.getFileName() + " exists: " + exists);

        if( exists) {
            boolean empty = Files.size(path) == 0;
            System.out.println("Empty: " + empty);
        }

        Files.write(path, lines, StandardCharsets.UTF_8);

        System.out.println("File written: " + path.getFileName());

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

用法

writeFile("c:/temp/test.txt", Arrays.asList("Some Text"));