您的位置:首页 > 编程语言 > Java开发

java的输入输出流与文件操作(2.读入写出及关流)

2017-12-09 20:37 477 查看
1.如何读取文件。

可以一个字节一个字节的读,也可以使用缓冲,一块一块数据的读。

一般使用第二种,因为比较快。

@Test
public void TestRead() throws IOException {
byte buf[] = new byte[1024];
FileInputStream fin = new FileInputStream("E:/test/io.txt");
int len = 0;
while((len=fin.read(buf)) != -1){
for (int i = 0; i < len; i++) {
System.out.print((char)buf[i]);
}
}
fin.close();
}

2.如何写出文件。

写出文件可以追加写出,也可以重新写出。

追加写出就是在原来文件的基础上继续追加内容。

重新写出就是擦除原来的文件内容,将新的内容写出到文件。

具体操作看代码。

@Test
public void TestOut() throws IOException{
byte buf[] = {65,66,49,48,13,10,97,98};
// FileOutputStream fout = new FileOutputStream("E:/test/io.txt");//重新写出方式
FileOutputStream fout = new FileOutputStream("E:/test/io.txt",true);//追加方式
fout.write(buf);
fout.close();
/* 控制台打印:
* AB10
* ab
* */
}

3.使用流之后关流的正确操作(IO异常处理的模板)

@Test
public void TestClose() {
byte buf[] = new byte[512];
int len = 0;
FileInputStream in = null;
try {
in = new FileInputStream("E:/test/io.txt");
while ((len = in.read(buf)) != -1) {
// bytes, offset, length ,charsetName
String string = new String(buf, 0, len, "gbk");
System.out.print(string);
}
} catch (FileNotFoundException e) {
System.err.println("找不到指定文件!");
// e.printStackTrace();
} catch (IOException e) {
System.err.println("文件读取失败");
// e.printStackTrace();
} catch (Exception e) {
// 作为补充
e.printStackTrace();
} finally {
try {
if (in != null) {// 不能为空(反正有点的都需要防护)
in.close();
}
} catch (IOException e) {
// 到这里情节已经很严重了,可能会丢失数据
throw new RuntimeException("关流失败",e);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: