字节流
项目文件路径
一个一个字节读取
//一个个字节读取
public static void run1() throws IOException{
//字节流
FileInputStream fis= null;
FileOutputStream fos=null;
String url1=InputOutputStream.class.getClassLoader().getResource("demo3.txt").getPath();
fis= new FileInputStream(url1);
fos= new FileOutputStream("demo1.txt");
int size=0;
while((size=fis.read())!=-1){
fos.write(size);
}
fis.close();
fos.close();
}
数组读取
//数组读取
private static final int BUFFER_SIZE = 1024;
public static void run2() throws IOException{
//字节流
FileInputStream fis= null;
FileOutputStream fos=null;
String url1=InputOutputStream.class.getClassLoader().getResource("demo3.txt").getPath();
fis= new FileInputStream(url1);
fos= new FileOutputStream("demo2.txt");
byte[] buf= new byte[BUFFER_SIZE];
int size=0;
while((size=fis.read(buf))!=-1){
fos.write(buf,0,size);
}
fis.close();
fos.close();
}
输入流输出流缓冲(缓冲流是处理流,是高级流,配合其他低级流使用)
//缓冲输入输出流
public static void run5() throws IOException{
BufferedInputStream bis= null;
FileOutputStream fos=null;
BufferedOutputStream bos= null;
InputStream inputStream = InputOutputStream.class.getClass().getResourceAsStream("/demo3.txt");
bis= new BufferedInputStream(inputStream);
fos= new FileOutputStream("demo5.txt");
bos= new BufferedOutputStream(fos);
int size=0;
/*while((size=bis.read())!=-1){
bos.write(size);
}*/
byte[] buf= new byte[BUFFER_SIZE];
while((size=bis.read(buf))!=-1){
bos.write(buf, 0, size);
}
bos.close();
bis.close();
fos.close();
}
混合使用
public static void run3() throws IOException{
BufferedInputStream bis=null;
FileOutputStream fos=null;
InputStream inputStream = InputOutputStream.class.getClass().getResourceAsStream("/demo3.txt");
bis= new BufferedInputStream(inputStream);
fos= new FileOutputStream("demo3.txt");
int size=0;
while((size=bis.read())!=-1){
fos.write(size);
}
bis.close();
fos.close();
}
public static void run4() throws IOException{
FileInputStream fis= null;
FileOutputStream fos=null;
BufferedOutputStream bos= null;
//类加载器,获取src根目录下文件路径
String url1=InputOutputStream.class.getClassLoader().getResource("demo3.txt").getPath();
//获取当前类文件所在包下的文件的路径
String path = InputOutputStream.class.getClass().getResource("/demo3.txt").getPath();
File file= new File(path);
//fis = new FileInputStream(url1);
fis = new FileInputStream(file);
fos = new FileOutputStream("demo4.txt");
bos = new BufferedOutputStream(fos);
int size=0;
while((size=fis.read())!=-1){
bos.write(size);
}
bos.close();
fis.close();
fos.close();
}