package Work;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.junit.Test;
public class Io {
@Test
public void testBufferRead() throws IOException {
// BufferedReader包装了字节流,并且可以按指定的编码集将字节转成字符
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("E:/download/a.txt")));
String line = br.readLine(); // 按照回车符来判断是否满一行,并用上面指定的编码集来将二进制数据转成字符串
System.out.println(line);
System.out.println("----------------");
while((line = br.readLine())!=null) {
System.out.println(line);
}
br.close();
}
@Test
public void testBufferWrite() throws IOException{
// true表示按追加的方式构造流, utf-8表示编码时所使用的编码集
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:/download/b.txt",true),"UTF-8"));
bw.write("我爱你,祖国\r\n"); // \r\n 在windows中是默认的换行符 而linux中默认的换行符:\n
bw.write("我爱你,contry");
bw.close();
}
@Test
public void testInputStream() throws IOException{
FileInputStream fs = new FileInputStream("E:/download/a.txt");
int num = 0;
byte[] buf = new byte[8];
while((num=fs.read(buf))!=-1) {
System.out.println(new String(buf,0,num));
}
fs.close();
}
@Test
public void testOutStream() throws IOException{
// @SuppressWarnings("resource")
FileOutputStream fs = new FileOutputStream("E:/download/b.txt");
String a="你好";
byte[] x = a.getBytes("UTF-8");
fs.write(x);
FileOutputStream fos = new FileOutputStream("E:/download/b.txt",true);
String s=" 中国";
byte[] xs = s.getBytes("UTF-8");
fs.write(xs);
fs.close();
fos.close();
}
}
java 以字符流和字节流读写文件
最新推荐文章于 2023-01-02 16:27:00 发布