gpt4 book ai didi

java - BufferedWriter - 未知来源异常

转载 作者:行者123 更新时间:2023-12-01 09:56:11 27 4
gpt4 key购买 nike

我正在制作一些名为 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();
}
}
}

附注抱歉,当我尝试将其放在这里时,缩进有点垃圾,是我的错:(

异常(exception)情况是:

[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)

最佳答案

我找到了答案:我必须只关闭 bw,然后它会自动关闭 fw。这就是异常(exception)情况

关于java - BufferedWriter - 未知来源异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37194057/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com