版权声明: https://blog.csdn.net/weixin_40072979/article/details/82998395
IO流操作的基标准步骤:
1:文件字节输入流 (将文件内容输入到程序中)
public static void main(String[] args) {
//1,创建源
File src = new File("abc.txt");
//2,选择流
InputStream in = null;
try {
in = new FileInputStream(src);
//3,操作(读取)
int temp=-1;
while((temp=in.read())!=-1){
System.out.println((char)temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//4.释放资源
try {
if(null == in){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们还可以来个缓冲,一次性读取多个字节数组。提高效率,
public static void main(String[] args) {
File src = new File("abc.txt");
InputStream in = null;
try {
in = new FileInputStream(src);
int temp=-1;
byte[] flush = new byte[3];
while((temp = in.read(flush))!=-1){
String str = new String(flush,0,temp);
System.out.print(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2:文件字节输出流 (将程序中的内容输出到文件中)
/**
* 文件字节输出流 (从程序输出到文件)
* 1,创建源
* 2,选择流
* 3,操作(写出内容)
* 4,释放资源
*/
public class IOTest04 {
public static void main(String[] args) {
//1,创建源
File dest = new File("dest.txt");
//2,选择流
OutputStream os = null;
try {
os = new FileOutputStream(dest,true);
//3,操作(写出)
String msg = "IO is so easy\r\n";
byte[] datas = msg.getBytes();//字符串 --> 字节数组(编码)
os.write(datas, 0, datas.length);
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//4,释放资源
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}