1 字节流 inputStream outputStream 接口
常见实现类 FileOutputStream FileOutputStream
ObjectOutputStream ObjectInputStream
BufferInputStream BufferOutputStream
2 字符流 Reader Writer 接口
常见实现类 FileReader FilerWritr
BufferReader BufferWriter
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建,如果要追加的话,在构造方法里加true
String str="Hello World";
byte[] b=str.getBytes();
out.write(b);//因为是字节流,所以要转化成字节数组进行输出
out.close();
}
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int len=in.read(b);
in.close();
System.out.println(new String(b,0,len));
}
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
Writer out=new FileWriter(f);
String str="Hello World";
out.write(str);
out.close();
}
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
Reader input=new FileReader(f);
char[] c=new char[1024];
int len=input.read(c);
input.close();
System.out.println(new String(c,0,len));
}
@RequestMapping("firstinput")
public void firstinput() throws Exception {
Reader reader = null;
BufferedReader br = null;
Writer writer = null;
BufferedWriter bw = null;
//第一部分:准备从文件读数据到程序
reader = new FileReader(new File("E:\\aa.txt"));
br = new BufferedReader(reader);//之所以这样做是因为 FileReader 没有提供读取文本行的功能
writer= new FileWriter(new File("E:\\bb.txt")) ;
bw = new BufferedWriter(writer);
String a=null;
while(( a=br.readLine())!=null) {
bw.write(a);
bw.newLine();
}
bw.flush(); //清空缓冲区
bw.close();
br.close();
}
转换 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));