java IO流的体系结构图
常用字节流字符流
字节流 InputStream 字符流 Reader
FileInputStream BufferedReader
FilterInputStream InputStreamReader
BufferedInputStream FileReader
DateInputStream StringReader
ObjectInputStream Writer
ByteArrayInputStream BufferedWriter
OutputStreamWriter
OutputStream FileWriter
FileOutputStream PrinterWriter
FilterOutputStream
BufferedOutputStream
DateOutputStream
ObjectOutputStream
ByteArrayOutputStream
java IO流使用的是装饰器设计模式。
FileInputSream/FileOutputStream
public class CharTest {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(new File("F:\\t.txt"));
fos=new FileOutputStream(new File("F:\\d.txt"));
int ch;
while((ch=fis.read())!=-1){
System.out.println((char)ch);
fos.write(ch);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedReader/BufferedWriter
public class BufferedInputStreamTest {
public static LinkedList<String> read(String fileName){
LinkedList<String> ll=null;
try {
BufferedReader br=new BufferedReader(
new FileReader(fileName));
BufferedWriter bw=new BufferedWriter(
new FileWriter("F:\\d.txt"));
ll=new LinkedList<String>();
String s;
while((s=br.readLine())!=null){
ll.add(s);
bw.write(s);
}
br.close();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ll;
}
public static void main(String[] args) {
LinkedList<String> s=read("F:\\t.txt");
for (String string : s) {
System.out.println(string);
}
}
}
字节流转换成字符流
public class ReadTest {
public static void main(String[] args) {
try {
BufferedReader br=new BufferedReader(
new InputStreamReader(
new FileInputStream("F:\\t.txt")));
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("F:\\d.txt")));
String s;
StringBuilder sb=new StringBuilder();
while((s=br.readLine())!=null){
System.out.println(s);
bw.write(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
用转换流从控制台上读入数据
public class SystemTest {
public static void main(String[] args) {
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
try {
String s=br.readLine();
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象流(将对象序列化,该对象要实现Serializable接口)
private static void writerFile() {
try {
ObjectOutputStream oo=new ObjectOutputStream(
new FileOutputStream(new File("F://test.txt")));
oo.writeObject(u);
oo.flush();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readFile() {try {
ObjectInputStream ois=new ObjectInputStream(
new FileInputStream(new File("F://test.txt")));
User o=(User)ois.readObject();
ois.close();
}
catch (Exception e) {
e.printStackTrace();
}
return ll;
}