流分为节点流和处理流
节点流是直接读到数据上
节点流有 FileInputStream/FileReader 输出流FileOutputStream(字节流)/FileWriter(字符流 可以输出一个汉字)
字符流:FileReader fr = new FileReader("d:/java/io/TestFileWriter2.java");
FileWriter fw = new FileWriter("d:/java/io/TestFileWriter2.bak");
int b;
while((b = fr.read()) != -1) {
fw.write(b);
}
fr.close();
fw.close();
字节流:int b = 0;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("d:/share/java/HelloWorld.java");
out = new FileOutputStream("d:/share/java/io/HW.java");
while((b=in.read())!=-1){
out.write(b);
}
in.close();
out.close();
处理流处理节点流的流
主要有 BufferedInputStream、BufferedReader
例如:BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\share\\java\\dat2.txt"));
BufferedReader br = new BufferedReader(
new FileReader("d:\\share\\java\\dat2.txt"));
String s = null;
for(int i=1;i<=100;i++){
s = String.valueOf(Math.random());
bw.write(s);
bw.newLine();
}
bw.flush();
while((s=br.readLine())!=null){
System.out.println(s);
}
bw.close();
br.close();
BufferedInputStream例子:FileInputStream fis =
new FileInputStream("d:\\share\\java\\HelloWorld.java");
BufferedInputStream bis =
new BufferedInputStream(fis);
int c = 0;
System.out.println(bis.read());
System.out.println(bis.read());
bis.mark(100);
for(int i=0;i<=10 && (c=bis.read())!=-1;i++){
System.out.print((char)c+" ");
}
System.out.println();
bis.reset();
for(int i=0;i<=10 && (c=bis.read())!=-1;i++){
System.out.print((char)c+" ");
}
bis.close();
节点流是直接读到数据上
节点流有 FileInputStream/FileReader 输出流FileOutputStream(字节流)/FileWriter(字符流 可以输出一个汉字)
字符流:FileReader fr = new FileReader("d:/java/io/TestFileWriter2.java");
FileWriter fw = new FileWriter("d:/java/io/TestFileWriter2.bak");
int b;
while((b = fr.read()) != -1) {
fw.write(b);
}
fr.close();
fw.close();
字节流:int b = 0;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("d:/share/java/HelloWorld.java");
out = new FileOutputStream("d:/share/java/io/HW.java");
while((b=in.read())!=-1){
out.write(b);
}
in.close();
out.close();
处理流处理节点流的流
主要有 BufferedInputStream、BufferedReader
例如:BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\share\\java\\dat2.txt"));
BufferedReader br = new BufferedReader(
new FileReader("d:\\share\\java\\dat2.txt"));
String s = null;
for(int i=1;i<=100;i++){
s = String.valueOf(Math.random());
bw.write(s);
bw.newLine();
}
bw.flush();
while((s=br.readLine())!=null){
System.out.println(s);
}
bw.close();
br.close();
BufferedInputStream例子:FileInputStream fis =
new FileInputStream("d:\\share\\java\\HelloWorld.java");
BufferedInputStream bis =
new BufferedInputStream(fis);
int c = 0;
System.out.println(bis.read());
System.out.println(bis.read());
bis.mark(100);
for(int i=0;i<=10 && (c=bis.read())!=-1;i++){
System.out.print((char)c+" ");
}
System.out.println();
bis.reset();
for(int i=0;i<=10 && (c=bis.read())!=-1;i++){
System.out.print((char)c+" ");
}
bis.close();