黑马程序员技术交流社区
标题:
关于IO问题求教,主要是异常处理
[打印本页]
作者:
luheqi
时间:
2014-6-27 18:46
标题:
关于IO问题求教,主要是异常处理
本帖最后由 luheqi 于 2014-6-28 12:22 编辑
第一段Test2:最后try里面的“bfw”部分报错通不过,而第二段正常,求解???
package com.company;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by he on 2014/6/27.
*/
public class Test2 {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("demo3.txt");
BufferedWriter bfw = new BufferedWriter(fw);
bfw.write("uasifuisbuisBufferedReaderbisb");
System.out.println("sdbjsd21515");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bfw.flush();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
第二段 Test:
package com.company;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
//public static final String LINE_SP = System.getProperty("line.separator");
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("demo.txt");
fw = new FileWriter("demo2.txt");
char[] buf = new char[1024];
int len = 0;
while ((len = fr.read(buf)) != -1) {
fw.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
if (fw != null)
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fr != null)
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
复制代码
作者:
luheqi
时间:
2014-6-27 18:57
代码改成这样就正常了:
package com.company;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by he on 2014/6/27.
*/
public class Test2 {
public static void main(String[] args) {
FileWriter fw = null;
BufferedWriter bfw = null;
try {
fw = new FileWriter("demo3.txt");
bfw = new BufferedWriter(fw);
bfw.write("uasifuisbuisBufferedReaderbisb");
System.out.println("sdbjsd21515");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bfw.flush();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
作者:
HF_Opticalix
时间:
2014-6-27 22:09
你自己不是回答了吗
BufferedWriter bfw = null 这个引用要建立在外面 才能在finally代码块中使用
作者:
luheqi
时间:
2014-6-28 12:18
嗯,已经解决,谢谢啦。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2