我有一個文本編輯器,它使用的代碼與下面的代碼幾乎完全相同,用於讀取和寫入。當我打開小文件進行編輯時,當我嘗試再次保存它們時,總會遇到此錯誤。但真正有趣的是,我的文本編輯器對於大約600字節或更多的文件(似乎每次都會有所不同)都能正常工作,這是我在這裏無法複製的行爲。FileNotFoundException在使用java讀取的同一文件上打開FileOutputStream時出現錯誤
我目前的解決方法是檢查1024字節的文件大小<,如果是這種情況,請使用java.io。
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Test {
public static void main(String[] args) {
String text = null;
try {
FileInputStream fis = new FileInputStream("test.txt");
FileChannel ifc = fis.getChannel();
CharBuffer cb = Charset.forName("ISO-8859-15").newDecoder().
decode(ifc.map(FileChannel.MapMode.READ_ONLY, 0,
(int) ifc.size()));
text = cb.toString();
ifc.close();
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter osw = new OutputStreamWriter(
fos, "ISO-8859-15");
osw.write(text);
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
對於上面的代碼,我得到這個錯誤test.txt的各種大小從4個字節到10KB:
java.io.FileNotFoundException: test.txt (The requested operation cannot be perfo
rmed 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 Test.main(Test.java:23)
任何人都可以解釋我做錯了,我怎麼能得到這工作,而仍然閱讀與尼奧?