流的输入及输出均是对程序而言
字节流输入
- 创建File对象,关联文件
File src = new File("D:/aa", "a.txt");
- 1)、创建以src为输入流的对象,
Inputstream in = new FileInputStream(src);
- 2)、建立字节数组(byte[]),创建长度整形变量len
byte[] car = new byte[10];
int len = 0;
- 3)、读取输入流,将byte[]转换为String并输出
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
read()返回读入长度,为-1时结束
2. 4)、读取结束后关闭输入流
代码语言:javascript复制in.close();
- 进行异常处理
try {
in = new FileInputStream(src);
byte[] car = new byte[10];
int len = 0;
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
System.out.println("文件读取失败");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("关闭输入流失败");
}
}
}
字节流输出
- 创建File对象,关联文件
File src = new File("D:/aa", "a.txt");
- 1)、创建以src为输出流的对象,
Outputstream in = new FileOutputStream(src);
- 2)、建立字符串,转换为字节数组并写入
String str = "simplen";
out.write(str.getBytes());
- 3)、刷新输出流
out.flush();
flush()方法使流中的数据写入文件
2. 4)、读取结束后关闭输出流
代码语言:javascript复制out.close();
- 进行异常处理
try {
out = new FileOutputStream(src, true);
String str = "simplen";
out.write(str.getBytes());
out.flush();
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("关闭输出流失败");
}
}
}
完整代码(输入):
代码语言:javascript复制package cn.hxh.io.filebyte;
import java.io.*;
public class myInputStream {
public static void main(String[] args) {
File src = new File("D:/aa", "a.txt");
InputStream in = null;
try {
in = new FileInputStream(src);
byte[] car = new byte[10];
int len = 0;
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
System.out.println("文件读取失败");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("关闭输入流失败");
}
}
}
}
}
完整代码(输出):
代码语言:javascript复制package cn.hxh.io.filebyte;
import java.io.*;
public class myOutputStream {
public static void main(String[] args) {
File src = new File("D:/aa", "a.txt");
OutputStream out = null;
try {
out = new FileOutputStream(src, true);
String str = "simplen";
out.write(str.getBytes());
out.flush();
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("关闭输出流失败");
}
}
}
}
}