java分享第七天-02(读取文件)

时间:2023-03-08 22:27:42

一 读取文件

public static void main(String[] args) throws FileNotFoundException,
IOException {
// 建立File对象
File srcFile = new File("");
// 选择流
InputStream isInputStream = null;// 提升作用域
try {
isInputStream = new FileInputStream(srcFile);
// 操作不断读取缓冲数组
byte[] car = new byte[10];
int len = 0;// 接收实际读取大小
// 循环读取
while (-1 != isInputStream.read(car)) {
// 输出字节数组转成字符串
String info = new String(car, 0, len);
System.err.println(info);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取文件失败");
} finally {
try {
if (null != isInputStream) {
isInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("关闭文件输入流失败");
}
} }

二写出文件

public static void main(String[] args) throws FileNotFoundException,
IOException {
// 建立File对象目的地
File dest = new File("");
// 选择流,文件输出流OutputStream FileOutputStream
OutputStream out = null;// 提升作用域
try {
//true以追加的形式写出文件,否则是覆盖
out = new FileOutputStream(dest,true);
String str="abcdedg";
//字符串转字节数组
byte[] data=str.getBytes();
out.write(data,0,data.length); out.flush();//强制刷新出去 } catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件未找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("写出文件失败");
} finally {
try {
//释放资源:关闭
if (null != out) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("关闭文件输出流失败");
}
} }