JAVA I/O系统
流(stream):
重(源)流向目的地
1. 当源是程序的时候:是输出流(outputstream)(细管道:按字节来输出流 粗管道:按字符输出流)
2. 当目的地是程序的时候:是输入流(inputstream)(细管道:字节输入流 粗管道:字符输入流)
判断输入、输出要站在程序的角度来看
流的分类
1. 字符流:面向字符的流,以字符为单位输入、输出数据,常用来操作字符类文件;
由于字符流是以字符为单位进行处理,所以其效率要由于字节流
2. 对象流:面向对象的流,将内存中的对象进行序列化,
或把序列化文件恢复成内存中的对象。可以长久的保存对象的信息及状态。
对象流是一种字节流,只不过它操作的是Object
对象的序列化:将对象以二进制流的形式输出(objectoutputstream是让对象变成二进制流)
对象的反序列化:将输入的二进制流转化为一个对象
序列化与反序列化
//对象序列化
//被序列化的类,必须实现Serializable这个接口
User user = new User("张三",18,false);
Address address = new Address("成都","红瓦寺", 17);
user.setMyAddress(address);
ObjectOutputStream oos = null;
try {
//ObjectOutputStream在设计时就是用来被对接的
oos = new ObjectOutputStream(new FileOutputStream("user.data"));
oos.writeObject(user);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(oos != null){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//反序列化
User user = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("user.data"));
user = (User)ois.readObject();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(ois != null){
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(user.getName() + " " + user.getMyAddress().getCity());
}
File
// TODO Auto-generated method stub
// File file = new File("E:/test");
// File[] subFiles = file.listFiles();//得到目录中所有的子文件对象(包括子文件夹)
// for(File subFile : subFiles){
// System.out.println(subFile.getPath());//得到文件的全路径名
// System.out.println(subFile.getParent());//得到文件的路径
// System.out.println(subFile.getName());//得到文件的文件名
// System.out.println(subFile.isDirectory());//得到File对象是否是目录
// System.out.println(subFile.length());//得到文件的大小
// System.out.println(new Date(subFile.lastModified()));
// System.out.println(subFile.getName() + "\t\t" + subFile.length() +
// "\t\t" + new Date(subFile.lastModified()));
// }
showSubFileName(new File("E:\\"));
}
public static void showSubFileName(File file) {
File[] subFiles = file.listFiles();
for (File subFile : subFiles) {
if (!subFile.isHidden()) {
if (subFile.isDirectory()) {
showSubFileName(subFile);
} else {
System.out.println(subFile.getPath());
}
}