版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21122243/article/details/77102903
文件的读取
- Test01_InputStream.java
package _02.io.byteStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 文件的读取
* 1.建立联系-> File对象(源头)
* 2.选择流-> 文件输入流 InputStream FileInputStream
* 3.操作 : byte[] car =new byte[1024]; + read + 读取大小
输出
* 4.释放资源 :关闭
*/
public class Test01_InputStream {
public static void main(String[] args) {
//1.建立联系 File对象
File src =new File("E:/IOTest/a.txt");
//2.选择流
InputStream is =null; //提升作用域
try {
is =new FileInputStream(src);
//3.操作 不断读取缓冲数组
byte[] flush =new byte[1024];
int len =0; //接收实际读取大小
//循环读取
StringBuilder sb =new StringBuilder();
while(-1!=(len=is.read(flush))){
//输出 字节数组转成字符串
String info =new String(flush,0,len);
sb.append(info);
}
System.out.println(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取文件失败");
}finally{
try {
//4.释放资源
if (null != is) {
is.close();
}
} catch (Exception e2) {
System.out.println("关闭文件输入流失败");
}
}
}
}
写出文件
- Test02_OutputStream.java
package _02.io.byteStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* 写出文件
* 1.建立联系->File对象(目的地)
* 2.选择流->文件输出流 OutputStream FileOutputStream
* 3.操作 : write() +flush
* 4.释放资源 :关闭
*
*/
public class Test02_OutputStream {
public static void main(String[] args) {
//1.建立联系->File对象(目的地)
File dest =new File("E:/IOTest/b.txt");
//2.选择流->文件输出流 OutputStream FileOutputStream
OutputStream os =null;
try {
os =new FileOutputStream(dest,true);//append为true以追加形式写出文件,否则为覆盖
//3.操作 : write() +flush
String str="zhushen is very kind men\r\n";
//字符串转字节数组
byte[] data =str.getBytes();
os.write(data,0,data.length);
os.flush(); //强制刷新出去
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件未找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件写出失败");
}finally{
//4.释放资源 :关闭
try {
if (null != os) {
os.close();
}
} catch (Exception e2) {
System.out.println("关闭输出流失败");
}
}
}
}