Java流和文件总结(二)
Print流1.TestPrintStream1.java
import java.io.*;public class TestPrintStream1 { public static void main(String[] args) { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream("d:\\bak\\log.dat"); ps = new PrintStream(fos); } catch (IOException e) { e.printStackTrace(); } if(ps != null){ System.setOut(ps); } int ln = 0; for(char c = 0; c <= 60000; c++){ System.out.print(c+ " "); if(ln++ >=100){ System.out.println(); ln = 0;} }}}
2.TestPrintStream2.java
import java.io.*;public class TestPrintStream2 {public static void main(String[] args) { String filename = args; if(filename!=null){list(filename,System.out);}}public static void list(String f,PrintStream fs){ try { BufferedReader br = new BufferedReader(new FileReader(f)); String s = null; while((s=br.readLine())!=null){ fs.println(s); } br.close(); } catch (IOException e) { fs.println("无法读取文件"); }}}
3.TestPrintStream3.java
import java.util.*; import java.io.*;public class TestPrintStream3 {public static void main(String[] args) { String s = null; BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); try { FileWriter fw = new FileWriter ("d:\\bak\\logfile.log", true); //Log4J PrintWriter log = new PrintWriter(fw); while ((s = br.readLine())!=null) { if(s.equalsIgnoreCase("exit")) break; System.out.println(s.toUpperCase()); log.println("-----"); log.println(s.toUpperCase()); log.flush(); } log.println("==="+new Date()+"==="); log.flush(); log.close(); } catch (IOException e) { e.printStackTrace(); }}}
Object流:
import java.io.*;public class TestObjectIO {public static void main(String args[]) throws Exception {T t = new T();t.k = 8;FileOutputStream fos = new FileOutputStream("d:/share/java/io/testobjectio.dat");ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(t);oos.flush();oos.close();FileInputStream fis = new FileInputStream("d:/share/java/io/testobjectio.dat");ObjectInputStream ois = new ObjectInputStream(fis);T tReaded = (T)ois.readObject();System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);}}class T implements Serializable{int i = 10;int j = 9;double d = 2.3;transient int k = 15;}
页:
[1]