我正在创建一些名为cake util的java库,其中一个是带有write()方法的WriteFile类。 现在,当我尝试调用该方法时,会发生未知来源异常
这是我的代码:
package Cake_Util.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import Cake_Util.console.Info;
import Cake_Util.console.Security;
public class WriteFile {
private File f;
public WriteFile(File path){
if(path.exists()){
this.f = path;
}else{
Info i = new Info("warn");
i.print("Warning! the file doesnt exist");
Security s = new Security();
s.stop();
}
}
public void write(String text){
FileWriter fw = null;
try {
fw = new FileWriter(f);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(text);
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void newLine(){
FileWriter fw = null;
try {
fw = new FileWriter(f);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.newLine();
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
P.S。对不起当我试图把它放在这里时,缩进有点垃圾,我的错:(
例外是:
[18:31:34 Info] Creating file...
java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.close(Unknown Source)
at Cake_Util.file.WriteFile.write(WriteFile.java:42)
at mainPackage.lol.main.ThisIsATest.main(ThisIsATest.java:18)
答案 0 :(得分:1)
我找到了答案: 我不得不只关闭bw然后会自动关闭fw。这就是例外