Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试从大型文本文件读/写时发生OutOfMemoryError_Java - Fatal编程技术网

Java 尝试从大型文本文件读/写时发生OutOfMemoryError

Java 尝试从大型文本文件读/写时发生OutOfMemoryError,java,Java,我正试图读/写一个巨大的文本文件。 但当我尝试这样做时,我得到了错误: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source) at java.lang.AbstractS

我正试图读/写一个巨大的文本文件。 但当我尝试这样做时,我得到了错误:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
    at java.lang.AbstractStringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at ReadWriteTextFile.getContents(ReadWriteTextFile.java:52)
    at ReadWriteTextFile.main(ReadWriteTextFile.java:148)
我的代码如下:

import java.io.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ReadWriteTextFile {

  /**
  * Fetch the entire contents of a text file, and return it in a String.
  * This style of implementation does not throw Exceptions to the caller.
  *
  * @param aFile is a file which already exists and can be read.
  */    
  static public String getContents(File aFile) {
    //...checks on aFile are elided
      StringBuilder contents = new StringBuilder(); 
      int maxlines = 1000; //counts max lines t read/write to the file
      BufferedReader input = null;
      BufferedWriter bw = null;

    try {
      //use buffering, reading one line at a time
      //FileReader always assumes default encoding is OK!
      input =  new BufferedReader(new FileReader(aFile));
      try {
          String line = null; //not declared within while loop
        /*
        * readLine is a bit quirky :
        * it returns the content of a line MINUS the newline.
        * it returns null only for the END of the stream.
        * it returns an empty String if two newlines appear in a row.
        */
        //for (int i = 0; i < 100; i++){
        //int count = 0;//initiates the line counter
      while (( line = input.readLine()) != null){

          int count = 0;//initiates the line counter    
          String modified1 = line.substring(2,17);
          String modified2 = line.substring(18,33);
          String modified3 = line.substring(40);        
          String result = "empty";
          result = modified1 + ",," +modified2 + modified3;
          System.out.println (result);          

//        contents.append(line);
//        contents.append(System.getProperty("line.separator"));
          //int count = 0;//initiates the line counter
          try {

              contents.append(line);
              contents.append(System.getProperty("line.separator"));
          String content = result;

          File file = new File("C:\\temp\\out.txt");//output path

          // if file doesnt exists, then create it
          if (!file.exists()) {
          file.createNewFile();
          }
          for ( int i = 0; i < 1000; i++){
              if (count++ % maxlines == 0) {
          FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
          bw = new BufferedWriter(fw);      
              bw.write(content);
          bw.newLine(); 
          }
          bw.close();
          }

        } catch (IOException e) {
            e.printStackTrace();
        }

        //}
        }
      }
      finally {
          input.close();
          bw.close();

      }
    }
    catch (IOException ex){
        ex.printStackTrace();
    }

    return contents.toString();
  }


/**
  * Change the contents of text file in its entirety, overwriting any
  * existing text.
  *
  * This style of implementation throws all exceptions to the caller.
  *
  * @param aFile is an existing file which can be written to.
  * @throws IllegalArgumentException if param does not comply.
  * @throws FileNotFoundException if the file does not exist.
  * @throws IOException if problem encountered during write.
  */
  static public void setContents(File aFile, String aContents)
                                 throws FileNotFoundException, IOException {
    if (aFile == null) {
        throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
        throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
        throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
        throw new IllegalArgumentException("File cannot be written: " + aFile);
    }

    //use buffering
    Writer output = new BufferedWriter(new FileWriter(aFile, true));
    try {
      //FileWriter always assumes default encoding is OK!
        output.write( aContents );
    }
    finally {
      output.close();
    }

  }

  /** Simple test harness.   */
  public static void main (String... aArguments) throws IOException {
      File testFile = new File("C:\\temp\\in.txt");//input path
      System.out.println("\n" + getContents(testFile));

  }

}
import java.io.*;
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileWriter;
导入java.io.IOException;
公共类ReadWriteTextFile{
/**
*获取文本文件的全部内容,并以字符串形式返回。
*这种类型的实现不会向调用方抛出异常。
*
*@param aFile是一个已经存在且可以读取的文件。
*/    
静态公共字符串getContents(文件文件){
//…删除文件上的检查
StringBuilder内容=新建StringBuilder();
int maxlines=1000;//计算读取/写入文件的最大行数
BufferedReader输入=null;
BufferedWriter bw=null;
试一试{
//使用缓冲,一次读取一行
//FileReader始终假定默认编码是正确的!
输入=新的BufferedReader(新的文件读取器(aFile));
试一试{
String line=null;//未在while循环中声明
/*
*readLine有点古怪:
*它返回一行内容减去换行符。
*它仅在流的末尾返回null。
*如果一行中出现两个换行符,则返回空字符串。
*/
//对于(int i=0;i<100;i++){
//int count=0;//启动行计数器
而((line=input.readLine())!=null){
int count=0;//启动行计数器
字符串modified1=行。子字符串(2,17);
String modified2=行。子字符串(18,33);
String modified3=行.子字符串(40);
String result=“empty”;
结果=修改后的1+“,”+修改后的2+修改后的3;
System.out.println(结果);
//内容。追加(行);
//append(System.getProperty(“line.separator”);
//int count=0;//启动行计数器
试一试{
内容。追加(行);
append(System.getProperty(“line.separator”);
字符串内容=结果;
File File=新文件(“C:\\temp\\out.txt”);//输出路径
//如果文件不存在,则创建它
如果(!file.exists()){
createNewFile();
}
对于(int i=0;i<1000;i++){
如果(计数+++%maxlines==0){
FileWriter fw=新的FileWriter(file.getAbsoluteFile(),true);
bw=新的缓冲写入程序(fw);
写(内容);
换行符();
}
bw.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
//}
}
}
最后{
input.close();
bw.close();
}
}
捕获(IOEX异常){
例如printStackTrace();
}
返回contents.toString();
}
/**
*更改文本文件的全部内容,覆盖任何
*现有案文。
*
*这种类型的实现向调用方抛出所有异常。
*
*@param aFile是一个可以写入的现有文件。
*@如果参数不符合要求,则抛出IllegalArgumentException。
*@如果文件不存在,则抛出FileNotFoundException。
*@在写入过程中遇到问题时引发IOException。
*/
静态公共void setContents(文件、字符串和内容)
抛出FileNotFoundException,IOException{
if(aFile==null){
抛出新的IllegalArgumentException(“文件不应为null”);
}
如果(!aFile.exists()){
抛出新的FileNotFoundException(“文件不存在:+aFile”);
}
如果(!aFile.isFile()){
抛出新的IllegalArgumentException(“不应该是目录:“+aFile”);
}
如果(!aFile.canWrite()){
抛出新的IllegalArgumentException(“无法写入文件:+aFile”);
}
//使用缓冲
Writer输出=新的BufferedWriter(新的FileWriter(aFile,true));
试一试{
//FileWriter始终假定默认编码是正确的!
输出。写入(aContents);
}
最后{
output.close();
}
}
/**简单的测试线束*/
公共静态void main(字符串…aArguments)引发IOException{
File testFile=新文件(“C:\\temp\\in.txt”);//输入路径
System.out.println(“\n”+getContents(testFile));
}
}
我尝试添加一个计数器(count),这样它可以在读取一定数量的行后刷新缓冲区。它不起作用。 我知道计数器工作不正常。在执行“while”循环的特殊次数后,它不会变为零。我在while循环之前和之后添加了一个“for”循环来清空计数器,但效果不太好


有什么建议吗?

不要试图将大文件读入内存。它们不合适。找到一种方法,一次处理一行文件,一次处理一条记录,一次处理一个块。我看不出你为什么不能这么做

在围绕同一
文件构建
FileWriter
之前,立即调用
文件.exists()
文件.createNewFile()
完全是浪费时间

我尝试添加一个计数器(count),这样它可以在读取一定数量的行后刷新缓冲区。它不起作用。我知道计数器工作不正常。在执行“while”循环的特殊次数后,它不会变为零。我在while循环之前和之后添加了一个“for”循环来清空计数器,但效果不太好

有什么建议吗

内存不足错误是因为文件太大,无法将该文件的所有内容读入函数
getContents(file aFile)
中的局部变量
contents

刷新缓冲区与此无关。使用而不是BufferedWriter可能有助于稍微清理代码。通过使用PrintWriter,您不必执行以下操作:

bw.write(content);
bw.newLine(); 
printWriter.println(content);
FileInputStream in = new FileInputStream(from); //Read data from a file
FileOutputStream out = new FileOutputStream(to); //Write data to a file
byte[] buffer = new byte[4096]; //Buffer size, Usually 1024-4096
int len;
while ((len = in.read(buffer, 0, buffer.length)) > 0) {
    out.write(buffer, 0, len);
}
//Close the FileStreams
in.close();
out.close();
// Removed redundant exists()/createNewFile() calls altogether
String line;
BufferedReader br = new BufferedReader(new FileReader(aFile));
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
while ((line = br.readLine()) != null) {
      String modified1 = line.substring(2,17);
      String modified2 = line.substring(18,33);
      String modified3 = line.substring(40); 
      String result = "empty";
      result = modified1 + ",," +modified2 + modified3;
      System.out.println (result);
      output.append(result + "\n");//Use \r\n for Windows EOL
}
//Close Streams
br.close();
output.close();
if(contents.length() => (Integer.MAX_VALUE-5000)) { //-5000 to give some headway when checking
    . . .
}