关于JAVA文件读入的问题

来源:百度知道 编辑:UC知道 时间:2024/04/28 17:03:55
我想从文件读入一个整数,用下面的程序
为什么会报错。。
我1.in 里只写了个1

package fileinputstream1;
import java.io.*;
public class FileInputStream1 {
public static void main(String[] args) {
int a=0;
try{
FileInputStream file1=new FileInputStream("1.in");
DataInputStream infile=new DataInputStream(file1);
FileOutputStream file2=new FileOutputStream("1.out");
DataOutputStream outfile=new DataOutputStream(file2);
a=infile.readInt();
a++;
outfile.write(a);
file1.close();
file2.close();
}
catch(Exception e)
{
System.out.println("not found file");
}
}

}

1.注意1.in文件的位置是否正确;
2.把infile.readInt()改为infile.read();

查看java api文档得到:
readInt
public final int readInt()
throws IOException参见 DataInput 的 readInt 方法的常规协定。
从所包含的输入流中读取此操作需要的字节。

指定者:
接口 DataInput 中的 readInt
返回:
此输入流的下四个字节,将它们解释为一个 int。
抛出:
EOFException - 如果此输入流在读取这四个字节之前到达末尾。
IOException - 如果发生 I/O 错误。