我用eclipse建了个工程
import java.io.*;
public class TestFile {
public static void main(String[] args) {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test2.txt");
pw.print("");
}
}但问什么老是报异常
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type FileNotFoundException at TestFile.main(TestFile.java:6)请问到底什么地方不对?请指教
import java.io.*;
public class TestFile {
public static void main(String[] args) {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test2.txt");
pw.print("");
}
}但问什么老是报异常
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type FileNotFoundException at TestFile.main(TestFile.java:6)请问到底什么地方不对?请指教
try catch
在使用FileWriter,PrintWriter这个两个类的构造方法都会抛出IOException,因为在写文件的时候会判断文件是否存在,比如:FileWriter fw = new FileWriter("k://test.txt");使用k://test.txt这样一个目录,显然硬盘上是不存在这样一个文件和盘符的,所以必须要捕获异常。你如果是用文本编辑器来写程序的话,建议遇到错误 ,先查查API文档。用eclipse或其它IDE开发工具,像这种错误都会时时提示你的。希望能帮到你!
try{
你的代码
}catch(Exception e){
}
包裹
读取数据会抛出io异常
要是觉得麻烦就直接throws Exception
不然就try catch处理了
try {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test2.txt");
pw.print("");
pw.close();
fw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class TestFile {
public static void main(String[] args)throws IOException {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test2.txt");
pw.print("");
}
}
抛个异常就行了
问题是test2.txt文件没有找到,对于eclipse来说是工程目录下没有此文件。
对于命令行程序来说是当前目录下没有此文件。
而且规范的代码书写要用try{}catch(){代码;}包裹。
如果用IDE则你那个程序书写时就会报错。