【问题标题】:Having problems with removing first line from txt file从 txt 文件中删除第一行时遇到问题
【发布时间】:2014-05-17 22:07:39
【问题描述】:

我知道这是非常基本的东西,但由于某种原因,我遇到了 bufferedReader/Writer 的问题。我正在尝试获取第一行文本并将其返回到另一种方法。但是,由于某种原因,作者似乎没有写入临时文件,也没有更改临时文件的名称。

通过抛出一些打印语句,我已经能够弄清楚:

  1. while 循环运行正常
  2. if else 语句运行正常
  3. tempFile 未正确写入文本文件
  4. tempFile 重命名不正确
  5. 没有错误被抛出

    私有静态字符串 wavFinder() 抛出 IOException{

        String currentWav=null;
        int x = 1;
        File inputFile = new File("C:\\convoLists/unTranscribed.txt");
        File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
        String currentLine = null;
    
        while((currentLine = reader.readLine()) != null) {
            if(x == 1){
                currentWav = currentLine;
            }
            else{
            writer.write(currentLine);
            }
            x = 2;
        }
        boolean successful = tempFile.renameTo(inputFile);      
        System.out.println("Success: " + successful);
        System.out.println("currentWav = " + currentWav);
        return currentWav;
    }
    

这是我正在使用的方法。如果您发现任何问题,请告诉我,如果您有任何问题,我一定会尽快回答。谢谢你:)

【问题讨论】:

  • 你关闭了作者吗?

标签: java bufferedreader bufferedwriter


【解决方案1】:
  1. 首先冲洗蒸汽(写入器)并关闭它们。
  2. 你不能有两个同名的文件。您正在尝试使用输入文件重命名临时文件。您需要删除输入文件,然后将其重命名为。

    reader.close(); writer.flush(); writer.close(); inputFile.delete();

在重命名之前添加这些行,它将起作用

【讨论】:

    【解决方案2】:

    在尝试调用 renameTo 之前关闭缓冲区。

    reader.close()
    writer.close()
    

    【讨论】:

      【解决方案3】:

      文件 inputFile = new File("C:\convoLists/unTranscribed.txt"); 文件 tempFile = new File("C:\convoLists/unTranscribedtemp.txt");

      为什么你有不同的路径标志?

      总是应该是 //。

      【讨论】:

        猜你喜欢
        • 2018-03-21
        • 1970-01-01
        • 2014-03-05
        • 2021-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多