回复 8楼 疯狂的小a
这是我记的File类的笔记,全部代码都在这里了。还是最后那个对象输出那有点问题。老司机,带带路。^_^
import *;
class Person implements Serializable
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public void print()
{
System.out.println(name);
System.out.println(age);
}
}
public class Files
{
public static void main(String args[])
{
byte a[]= {1,2,3};
//创建文件对象
File f1 = new File("F:\\file","name.txt");
System.out.println(f1.getName());
//写入字节流
try
{
FileOutputStream out = new FileOutputStream(f1);
out.write(a);
out.close();
System.out.println("写入成功!");
}
catch(IOException e3)
{System.out.println("Error");}
//读取字节流
try
{
int n=-1;
FileInputStream in = new FileInputStream(f1);
System.out.println("读取...");
while((n=in.read())!=-1)
{
System.out.println(n);
}
in.close();
}
catch(IOException e4)
{System.out.println("Error");}
//创建对象
File f2 = new File("F:\\file","name2.txt");
System.out.println(f2.getName());
//写入字符流
try
{
FileWriter out = new FileWriter(f2);
char c[]={'a','b','c'};
out.write(c);
out.close();
System.out.println("写入成功!");
}
catch(IOException e2)
{System.out.println("Error");}
//读取字符流
try
{
FileReader in = new FileReader(f2);
int n=-1;
System.out.println("读取...");
while((n=in.read())!=-1)
System.out.println((char)n);
in.close();
}
catch(IOException e1)
{System.out.println("Error");}
//缓冲流(按行操作字符流)
File f3 = new File("F:\\file","name3.txt");
System.out.println(f3.getName());
String contents[]={"上海","北京","广州","深圳"};
//写入缓冲流
try
{
FileWriter fx= new FileWriter(f3);
BufferedWriter out = new BufferedWriter(fx);
for(String element:contents)
{
out.write(element);
out.newLine();//输出一个行分隔符
}
System.out.println("写入成功!");
out.close();
fx.close();
}
catch(IOException e9)
{System.out.println("Error2");}
//读取缓冲流
try
{
FileReader fy= new FileReader(f3);
BufferedReader in = new BufferedReader(fy);
String s=null;
System.out.println("读取...");
while((s=in.readLine())!=null)
System.out.println(s);
in.close();
fy.close();
}
catch(IOException e99)
{System.out.println("error1");}
//序列化和反序列化
try
{
File file = new File("F:\\file","name6.txt");
System.out.println(file.getName());
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
Person person=new Person("krusl",12);
out.writeObject(person);
//序列化
out.close();
}
catch(IOException e22)
{
System.out.println("Errorrrrrr");
}
try
{
File file = new File("F:\\file","name6.txt");
//反序列化
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
Object newperson = in.readObject();
in.close();
System.out.println(newperson.name);
}
catch(IOException e999)
{System.out.println("ssss");}
catch(ClassNotFoundException E111)
{System.out.println("fdfdfd");}
}
}