文件读写

Serialization


FileOutputStream 把字节写入文件
ObjectOutputStream 把对象转换成可以写入串流的数据

序列化对象写入文件
(1)
FileOutputStream fileStream = new FileOutputStream("MyGame.ser");//若文件不存在,则会自动创建
(2)
ObjectOutputStream os = new ObjectOutputStream(fileStream);
(3)写入对象
os.writeObject(characterOne);
os.writeObject(characterTwo);//character* 必须要实现序列化
os.writeObject(characterThree);//writeObject()方法,会将对象打成串流送到FileOutputStream来写入文件

(4)关闭ObjectOutputStream
os.close();


让类实现实例化,就让该类实现Serializable接口。
当对象被序列化是,该对象引用的实例变量也会被序列化。

transient 标记某实例变量时,表示该变量不能或不应该被序列化,序列化程序会跳过该变量

Deserialization
(1)
FileInputStream fileStream = new FileInputStream("MyGame.ser");//若文件不存在,则会抛出异常
(2)
ObjectInputStream os = new ObjectInputStream(fileStream)
(3)读取对象
Object one = os.readObject();
Object two = os.readObject();
Object three = os.readObject();//每次调用readObject()都会动stream中读出下一个对象,读取书序与写入顺序相同,次数超过会抛出异常
(4)转换对象类型
GameCharacter elf = (GameCharacter) one;
GameCharacter troll = (GameCharacter) two;
GameCharacter magician = (GameCharacter) three;
(5)关闭ObjectInputStream
os.close();//FileInputStream会自动跟着关闭


把字符串写入文本文件
FileWriter writer = new FileWriter("Foo.txt");
writer.write("hello foo!");
writer.close();

File对象 代表磁盘上的文件或目录的路径名称

用途:
(1)创建出代表现存盘文件的File对象

File f = new File("MyCode.txt");

(2)建立新的目录

File dir = new File("Chapter7");
dir.mkdir();

(3)列出目录下得内容

if(dir.isDirectory()){
String[] dirContents = dir.list();
for(int i = 0;i < dirContents.lengh; i++){
System.out.println(dirContents[i]);
}
}

(4)取得文件或目录的绝对路径

System.out.println(dir.getAbsolutePath());

(5)删除文件或目录

boolean isDeleted = f.delete();


BufferedWriter writer = new BufferedWriter(new FileWriter(aFile));
writer.flush();//强制缓冲区立即写入


读取文本文件
try{
File f = new File("MyText.txt");
FileReader fileReader = new FileReader(f);
BufferedReader reader = new BufferedReader(fileReader);//只有在缓冲区读空的时候才回去磁盘读取,以获取更高的效率
String line = null;
while( (line = reader.readLine()) != null ){
System.Out.println(line);
}
reader.close();
}catch(Excepton e){
e.printStackTrace();
}

写入文本文件

try{
File file = new File("XXX.xml");
Reader reader = ...;
Writer writer = new BufferedWriter(new FileWriter(file));
char[] buff = new char[1024];
for(int i=0;(i=reader.read(buff))>0;){
writer.write(buff,0,i);
}
writer.close();
reader.close();
}catch(Exception e){
e.printStackTrace();
}

解析字串
String s = "a/b/c"
String[] argS = s.split("/");//split()方法会用参数所指定的字符拆开字符串,并存入数组

 

posted @ 2018-04-07 20:38  Rage_Leila  阅读(136)  评论(0编辑  收藏  举报