【Java-40】基于Java的IO流处理——字节数组流

模拟一

这里模拟一个功能,将一个字符串转换为字节数组流,然后通过字节流传进入字节数组,通过读方法得到字节数组之后通过流读取得到字节数组再得到字符串输出

字符串——字节数组——字节数组流——字节数组——字节数组流——字符串

package File_some;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;


/**
 * 这里模拟一个功能,将一个字符串转换为字节流,然后通过字节流传进入字节数组上
 * 读方法得到字节数组之后通过流读取得到字节数组
 * @author My_2
 *
 */
public class other_Scream {
public static void main(String[] args) throws IOException {
	
	other_Scream.read(other_Scream.writer());
}
public static byte[] writer() throws IOException {
	String str="大脸妹";
	byte by[]=str.getBytes();
	ByteArrayOutputStream out=new ByteArrayOutputStream();//加入流目的是使byte类型传输!传输
	out.write(by, 0, by.length);
	
	byte by2[]=out.toByteArray();
	return by2;
}

public static void read(byte data[]) throws IOException {
	InputStream input=new BufferedInputStream(new ByteArrayInputStream(data));
	byte flu[]=new byte[100];
	 int len;
	 while((len=input.read(flu))!=-1){
		 String str=new String(flu, 0, len);
		System.out.println(str);
	 }	
}

}

模拟二:

文件——字节数组流——文件

package File_some;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//将文件内容读到字节输入流中,再将字节流转为字节数组输出流,由字节数组流得到字节数组
//将字节数组转为字节数组输入流,将字节数组输入流转为字节输出流
//只有字节数组输出流才能转为字节数组
//字节输出流、输入流由文件得到,字节数组输入流、输出流由字节数组得到
public class all_excise {
public static void main(String[] args) throws IOException {
	String Path2="C:/A_Java/Project_1/src/File_some/Txt_file.java";
	File file2=new File(Path2);
	String Path3="C:/A_Java/Project_1/综合.txt";
	File file3=new File(Path3);
	writer(read(file2),file3);
}

public static byte[] read(File file) throws IOException {
	InputStream ins=new BufferedInputStream(new FileInputStream(file));//输入流、
	ByteArrayOutputStream out=new ByteArrayOutputStream();
	byte flu[]=new byte[1024];
	 int len;
	 while((len=ins.read(flu))!=-1){
		 out.write(flu, 0, len);
	 }
	 out.flush();
	 ins.close();
	return out.toByteArray();
	
}

public static void writer(byte by[],File file) throws IOException {
	OutputStream outs=	new BufferedOutputStream(new FileOutputStream(file));//输出流
	InputStream input=new ByteArrayInputStream(by);
	byte flu[]=new byte[1024];
	 int len;
	 while((len=input.read(flu))!=-1){
		 outs.write(flu, 0, len);
	 }
	 outs.flush();

	
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42034217/article/details/86661143
今日推荐