【java】内存流:java.io.ByteArrayInputStream、java.io.ByteArrayOutputStream、java.io.CharArrayReader、java.io.CharArrayWriter

时间:2023-09-23 11:45:38
 package 内存流;

 import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; public class Test {
public static void main(String[] args) throws IOException {
String str="Hello World!中国好国国国。";
InputStream in=new ByteArrayInputStream(str.getBytes());
OutputStream out=new ByteArrayOutputStream();
int tmp=0;
while((tmp=in.read())!=-1)
out.write(Character.toUpperCase(tmp));
System.out.println(out);//HELLO WORLD!中冠好冠冠冠。
//中文有乱码!!!
in.close();
out.close();
}
}

字节数组字节输入输出内存流

 package 内存流;

 import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer; public class Test {
public static void main(String[] args) throws IOException {
String str="Hello World!中国好国国国。";
Reader in=new CharArrayReader(str.toCharArray());
Writer out=new CharArrayWriter();
int tmp=0;
while((tmp=in.read())!=-1)
out.write(Character.toUpperCase(tmp));
System.out.println(out);//HELLO WORLD!中国好国国国。
//字符流处理中文无乱码!!!
in.close();
out.close();
}
}

字符数组字符输入输出内存流

 package 内存流;

 import java.io.*;

 public class Test {
public static void main(String[] args) throws IOException {
File[] files={
new File("D:"+File.separator+"testA.txt"),
new File("D:"+File.separator+"testB.txt"),
};
Reader[] ins={
new FileReader(files[0]),
new FileReader(files[1])
};
Writer out=new CharArrayWriter();
int tmp=0;
while((tmp=ins[0].read())!=-1)
out.write(tmp);
while((tmp=ins[1].read())!=-1)
out.write(tmp);
System.out.println(out.toString());
// System.out.println(new String(out.toCharArray()));
//字节内存输出流ByteArrayOutputStream下有个类似的toByteArray()方法
ins[0].close();
ins[1].close();
out.close();
}
}

将多个文件读入到同一个内存输出流