java中输入输出流主要由四个抽象类表示:字节流:InputStream、OutputStream 字符流:Reader、Writer
根据功能层次的不同:分为节点流和处理流
Example:
package com.test;
import java.io.*;
public class streamtest {
public static void main(String[] args)throws IOException
{
File f=new File("C:\\1.txt");
String str="FileReader and FileWriter";
char[] buffer=new char[str.length()];
buffer=str.toCharArray();
try
{
if(!f.exists())
f.createNewFile();
FileWriter fw=new FileWriter(f);
fw.write(buffer);
fw.close();
FileReader fr=new FileReader(f);
char[] result=new char[20];
int amount=fr.read(result);
System.out.println("total amount: "+amount);
System.out.println(result);
FileReader frobo=new FileReader(f);
char[] onebyone=new char[100];
int i=0;
System.out.println("read one by one");
while(i!=-1)
{
i=frobo.read();
if(i!=-1)
System.out.print(String.valueOf(Character.toChars(i))+"("+i+");");
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
total amount: 20
FileReader and FileW
read one by one
F(70);i(105);l(108);e(101);R(82);e(101);a(97);d(100);e(101);r(114); (32);a(97);n(110);d(100); (32);F(70);i(105);l(108);e(101);W(87);r(114);i(105);t(116);e(101);r(114);
Process finished with exit code 0
Example
package com.test;
import java.io.*;
public class inoutstream {
public static void main(String[] args)throws IOException
{
File f1=new File("C:\\1.txt");
File f2=new File("C:\\1new.txt");
FileInputStream fis=new FileInputStream(f1);
FileOutputStream fos=new FileOutputStream(f2);
byte[] b=new byte[(int) f1.length()];
fis.read(b);
for(int i=0;i<f1.length();i++)
{
fos.write(b[i]);
}
System.out.println("Done");
fis.close();
fos.close();
}
}