字节流和字符流小练习
1 FileOutputStream
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("/Users/mima000000/Desktop/1.txt",false); //true表示追加
// 每次写出一个字节数据
fos.write(97); //a
fos.write(98); //b
//换行
fos.write("\r".getBytes());
// 写出字节数组
byte[] bytes = " 不想加班".getBytes();
fos.write(bytes);
fos.close();
}
}
2 FileInputStream
2-1 每次读取1个字节
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("/Users/mima000000/Desktop/1.txt");
//每次读取一个字节数据
int b;
while ((b=fis.read())!=-1){
System.out.println((char)b);
}
fis.close();
}
}
2-2 使用有效字节数组读取
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("/Users/mima000000/Desktop/1.txt");
//每次读取一个字节数据
int b;
// 使用字节数组读取,每次最多读取2个字节
byte[] bytes = new byte[2];
while ((b= fis.read(bytes))!=-1){
System.out.println(new String(bytes,0,b));
}
fis.close();
}
}
3 FileReader
3-1 每次读取一个字符数据
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
public class test {
public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("/Users/mima000000/Desktop/1.txt");
int b;
while ((b=fileReader.read())!=-1){
System.out.println((char)b);
}
}
}
3-2 使用字符数组读取
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
public class test {
public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("/Users/mima000000/Desktop/1.txt");
int b;
char[] temp = new char[2];
while ((b=fileReader.read(temp))!=-1){
String res = new String(temp, 0, b);
System.out.println(res);
}
}
}
4 FileWriter
import java.io.*;
public class test {
public static void main(String[] args) throws Exception {
FileWriter fileWriter = new FileWriter("/Users/mima000000/Desktop/1.txt");
// 写字符串
fileWriter.write("你好");
//写字符数组
char[] temp = {'e','t'};
fileWriter.write(temp);
//写单个字符
fileWriter.write('g');
//刷新缓冲
fileWriter.flush();
//关闭
fileWriter.close();
}
}
我对任何唾手而得,快速,出自本能,即兴,含混的事物没有信心。我相信缓慢,平和,细水长流的力量,踏实,冷静。我不相信缺乏自律精神和不自我建设,不努力,可以得到个人或集体的解放。