繁体   English   中英

我无法将所有数据写入文件

[英]I am not able to write all data to a file

我编写了Java代码以从一个文件读取并写入新文件。 我正在读取的文件有5000行记录,但是当我写一个新文件时,我只能写4700-4900条记录。

我想可能是我正在同时读取文件并写入文件,这可能会造成问题。

我的代码如下:

从文件读取:

public String readFile(){
    String fileName = "/home/anand/Desktop/index.txt";
    FileReader file = null;  
    try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        String line = "";
        while ((line = reader.readLine()) != null) {
            line.replaceAll("ids", "");
            System.out.println(line);
            returnValue += line + "\n";
        }
        return returnValue;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                // Ignore issues during closing 
            }
        }
    }
}

写入文件:

public void writeFile(String returnValue){
    String newreturnValue = returnValue.replaceAll("[^0-9,]", "");      
    String delimiter = ",";
    String newtext ="";
    String[] temp;
    temp = newreturnValue.split(delimiter);
    FileWriter output = null;
    try {
        output = new FileWriter("/home/anand/Desktop/newinput.txt");
        BufferedWriter writer = new BufferedWriter(output);
        for(int i =0; i < temp.length ; i++){
            writer.write("["+i+"] "+temp[i]);
            writer.newLine();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                // Ignore issues during closing
            }
        }
    }
}

我需要有关如何同时读取和写入文件的建议。

您需要关闭writer而不是output BufferedWriter可能不会写入所有行,并且因为您永远不会关闭它而不会写入。

您必须关闭writer对象。 最后几行可能尚未刷新到文本文件上。

此外,您是否知道Java 7中引入的try-with-resource? 您可以利用以下代码将代码压缩:

 public String readFile(){
      String fileName = "/home/anand/Desktop/index.txt";

      try(BufferedReader reader = new BufferedReader(new FileReader(filename)) {

        String line = "";
        while ((line = reader.readLine()) != null) {
               line.replaceAll("ids", "");
               System.out.println(line);
               returnValue += line + "\n";
             }
        return returnValue;
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
    }

这样,一旦try块完成,Java就会自动为您关闭reader对象,而不管是否引发异常。 这使得阅读代码更容易:)

暂无
暂无

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

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