字符輸出流,轉換流,對象輸入/輸出流

private static void objectInputStream() {
		// TODO Auto-generated method stub
		try {
			FileInputStream fis=new FileInputStream("c:\\hello.txt");
			ObjectInputStream ois=new ObjectInputStream(fis);
			List<Student> list=(List<Student>) ois.readObject();
			for(Student s:list)
			{
				System.out.println(s.getStuid()+" "+s.getStuName());
			}
			ois.close();
			fis.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void objectOutputStream() {
		// TODO Auto-generated method stub
		//創建list集合並添加數據
		List<Student> list=new ArrayList<Student>();
		list.add(new Student("01","李白"));
		list.add(new Student("02","李商隱"));
		try {
			//文件輸出流創建對象,創建對象輸出流
			FileOutputStream fos=new FileOutputStream("c:\\hello.txt");
			ObjectOutputStream oos=new ObjectOutputStream(fos);	
			oos.writeObject(list);//將對象寫進文件
			oos.close();
			fos.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private static void inputStreamRead() {
		// TODO Auto-generated method stub
		InputStreamReader isr=new InputStreamReader(System.in);//轉換流,把字節流轉換爲字符流
		BufferedReader br=new BufferedReader(isr);//讀取進逐行流
		String str = null;
		try {
			str = br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str);
		try {
			br.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			isr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void fileWriter() {
		// TODO Auto-generated method stub
		try {
			FileWriter fw=new FileWriter("c:\\hello.txt");//字符輸出流
			BufferedWriter bw=new BufferedWriter(fw);//字符流讀進逐行流
			bw.write("逐行流寫");
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

對象類要實現序列化接口:

public class Student implements Serializable {
	private String stuid;
	private String stuName;

	public Student(String stuid, String stuName) {
		super();
		this.stuid = stuid;
		this.stuName = stuName;
	}

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	public String getStuid() {
		return stuid;
	}

	public void setStuid(String stuid) {
		this.stuid = stuid;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章