Java中的文件覆盖-用户映射部分打开错误

leb*_*lev 5 java overwrite

编写Java程序中的以下函数是为了读取文件,然后覆盖该文件。

public static void readOverWrite(File dir) throws IOException {
    for (File f : dir.listFiles()) {
        String[] data = readFile(f).split("\n");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {
            for (int i = 0; i < data.length; i++) {
                writer.write((data[i]+"\n"));
            }
            writer.close();
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

关于尝试运行程序的错误消息是:

Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileWriter.<init>(Unknown Source)
    at General.SplitCreationDate.splitLine(SplitCreationDate.java:37)
    at General.SplitCreationDate.main(SplitCreationDate.java:53)
Run Code Online (Sandbox Code Playgroud)

寻求帮助以解决错误。


readFile的代码

protected static String readFile(File fullPath) throws IOException {
    try(FileInputStream stream = new FileInputStream(fullPath)) {
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        stream.close();
        return Charset.defaultCharset().decode(bb).toString();
    }
} 
Run Code Online (Sandbox Code Playgroud)

读入另一个线程,这是Windows问题,因此readFile方法中的MappedByteBuffer就是问题的原因。重新编写readFile方法,如下所示。有用!

protected static String readFile(File fullPath) throws IOException {
    String string = "";
    try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) {
        String str;
        while ((str = in.readLine()) != null) {
            string += str + "\n";
        }
    }
    return string;
} 
Run Code Online (Sandbox Code Playgroud)

Vis*_*ons 1

打开文件流后,您需要将其关闭,否则它们仍会存在于您的系统中。这可能会导致腐败和类似的错误。查看有关文件 I/O 的 Java 学习教程本教程也展示了方法。

import java.io.*;

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();

    try {
      //use buffering, reading one line at a time
      //FileReader always assumes default encoding is OK!
      BufferedReader 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.
        */
        while (( line = input.readLine()) != null){
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }

    return contents.toString();
  }
Run Code Online (Sandbox Code Playgroud)

注意finally块。这可以确保无论是否发生异常,流都会关闭。您应该使用一个来关闭打开的流。