java IO 字节流最常用两种读写方式
随笔记录
今天在看导入功能开发时顺便动手敲了一下Java io字节流读写的代码,感觉简单,但是深刻理解还是需要话功夫研究,也在博客中mark一下,便于温故知新
package com.gsww.jzfp.commons;
import java.io.*;
/**
* Description:java IO 流学习
*/
public class JavaIODeamo {
public static void main(String[] args) {
File file =new File("D:\\copy_nginx.conf");
try {
//getFileByOutPutStream(file);
getFileByBufferedOutPutStream(file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 利用 字节流 读取文件、写入文件
* @param file
*/
private static void getFileByOutPutStream(File file) throws IOException {
//读取文件
InputStream in = new FileInputStream(new File("D:\\nginx.conf"));
//写出文件
//1、判断文件是否存在
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
//2、定义输出字节长度
byte[] bytes=new byte[2018];
int len= -1;
//3、循环输出
while ((len = in.read(bytes,0,bytes.length))!=-1){
//转换成字符串
String str = new String(bytes,0,len,"GBK");
System.out.println(str);
//输出
out.write(bytes,0,len);
}
out.flush();
in.close();
out.close();
}
/**
* 利用 缓冲字节流 读取文件、写入文件
* @param file
*/
private static void getFileByBufferedOutPutStream(File file) throws IOException {
//读取文件
BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("D:\\nginx.conf")));
//写出文件
//1、判断文件是否存在
if(!file.exists()){
file.createNewFile();
}
//2、输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
//定义字节长度
byte[] bytes = new byte[2048];
int len = -1;
//循环写出
while ((len = in.read(bytes, 0, bytes.length)) != -1) {
//可以转换字符流
String Str = new String(bytes, 0, len, "GBK");
System.out.println(Str);
//字节输出
out.write(bytes,0,len);
}
out.flush();
in.close();
out.close();
}
}