FileWriter未写入文件

问题描述 投票:0回答:2

我已经编写了一个程序,该程序应该从现有文件中获取一个值,将该值添加一个,删除该文件,创建该文件的新实例,并将新值写入该文件的新实例。

public static void main(String[] args) throws InterruptedException, IOException {

    //initialize newFile and writer
    File newFile = new File("C:\\Users\\boung\\Desktop\\python\\daysSince.txt");
    FileWriter writer = new FileWriter("C:\\Users\\boung\\Desktop\\python\\daysSince.txt", true);

    //if newFile doesn't exist or of newFile doesn't contain any content, create newFile and write "1" to newFile
    if(newFile.length() == 0) {

        System.out.println("empty");
        writer.write("1");
        writer.write("\r\n");
        writer.close();

    } else {

        //get contents of newFile
        StringBuilder contentBuilder01 = new StringBuilder();                       
        try (Stream<String> stream = Files.lines( Paths.get("C:\\Users\\boung\\Desktop\\python\\daysSince.txt"), StandardCharsets.UTF_8)) {

                stream.forEach(s -> contentBuilder01.append(s).append("\n"));

            } catch (IOException e) {

                e.printStackTrace();

            }

        //convert content to integer
        String content = contentBuilder01.toString();
        content = content.replaceAll("\\D+", "");
        int value = Integer.parseInt(content);
        System.out.println(value);

        //add 1 to the value that was returned from getting the contents of newFile and assign it to newValue
        int newValue = value + 1;

        //delete newFile
        newFile.delete();

        //create new instance of newFile to prepare for next execution
        if(newFile.length() == 0) { 
        newFile = new File("C:\\Users\\boung\\Desktop\\python\\daysSince.txt");
        }

        FileWriter writer1 = new FileWriter("C:\\Users\\boung\\Desktop\\python\\daysSince.txt", true);          

        //write newValue to new instance of newFile
        writer1.write(newValue);
        System.out.println("printed " + newValue);
        writer1.write("\r\n");
        writer1.close();
    }



}       

此区域出现问题

        writer1.write(newValue);
        System.out.println("printed " + newValue);
        writer1.write("\r\n");
        writer1.close();

假设newFile不存在,在两次运行该程序后,预期输出将如下所示

2

但这是我得到的输出

1

但是如果文件为空或不存在,程序在此处将1写入文件没有问题

    System.out.println("empty");
    writer.write("1");
    writer.write("\r\n");
    writer.close();

我假设我在程序逻辑上犯了一个错误,有人可以帮忙吗?

java filewriter file-writing
2个回答
1
投票

我相信您的程序有两个问题:


0
投票

newFile.delete();是不必要的,您无需删除文件即可再次写入。以下代码示例适用于我并正确输出。

© www.soinside.com 2019 - 2024. All rights reserved.