@Senl
2017-03-30T04:15:14.000000Z
字数 3085
阅读 1141
技术学习
Java的输入/输出带有连接类型的串流,它代表来源与目的地之间的连接,连接串流将串流与其他串流连接起来
对象序列化的时候,对象的状态-实例变量将会被保存,而如果该对象中有对其他对象引用的时候,所有被引用的对象爷将被序列化
需要序列化的类以及其引用的类,需要在声明的时候implements Serializable,否则会造成编译不通过(序列化是全部序列化或者全部不序列化的)
可以用trasient标记变量,此时该变量
//Person类import java.io.*;public class Person implements Serializable{private int money; //设置三个私有属性,一个静态变量,一个transient变量测试private int height;public String name;static String Live;transient String sex;public void setMoney(int money) {if(money>0){this.money = money;}}public void setHeight(int height) {if(height>0){this.height = height;}}public void setName(String name) {this.name = name;}public static String getLive() {return Live;}public static void setLive(String live) {Live = live;}public void setSex(String sex) {this.sex = sex;}public void show() {System.out.println("name:"+name+"money:"+money+"\t"+"height:"+height+"\t");System.out.println(sex+Live);}}
//Person启动类import java.io.*;public class CreatePerson {public static void main(String[] args) {// TODO Auto-generated method stubPerson boy = new Person(); //创建一个boy为Person类引用对象boy.setHeight(183); //通过三方法设置boy属性boy.setMoney(400);boy.setName("senl");boy.setSex("male");Person girl = new Person();//创建一个girl引用为Person类引用变量girl.setHeight(160);girl.setMoney(1000000);girl.setName("yu");girl.setSex("female");Person.setLive("yes");try{ //序列化FileOutputStream fs = new FileOutputStream("Person.ser");ObjectOutputStream os = new ObjectOutputStream(fs);os.writeObject(boy);os.writeObject(girl);os.close();}catch(Exception ex){ex.printStackTrace();}boy =null; //空置引用变量girl =null;try { //解序列化ObjectInputStream is = newObjectInputStream(new FileInputStream("Person.ser"));//转换对象类型Person boySaved = (Person) is.readObject();Person girlSaved = (Person)is.readObject();is.close();boySaved.show();girlSaved.show();} catch(Exception ex) {ex.printStackTrace();}}}
测试结果:name:senlmoney:400 height183null yesname:yumoney:1000000 height160null yes
try{FileWriter writer = new FileWriter("saved.txt");writer.writer("hello world");writer.cloes();} catch(IOException ex) {ex.printStackTrace();}
File f = new File("Saved code.txt") 建立一个新的目录
File dir = new File("Chapter 7");dir.mkdir();
列出目录下的内容
if(dir.isDirectory()) {String[] dirContents = dir.list();for(int i = 0;i<dirContents.length;i++){System.out.println(dirContents[i]);}}
取得文件或者目录的绝对路径
System.out.prinltln(dir.getAbsolutePath());
删除文件或者目录(成功讲返回true)
boolean isDeleted = f.delete();
try{File myFile = new File("my Text.txt");FileReader fileReader = new FileReader(myFile);BufferedReader reader = new BufferedReader(fileReader);//缓冲读取,提高效率String line = null;while((line = reader.readLine()) != null) {System.out.println(line)\}reader.close();}catch(Exception ex) {ex.printStackTrace();}