properties
/**
*生成properties文件
*/
@Test
public void demo() throws Exception {
Properties properties = new Properties();
properties.setProperty("1","小马");
properties.setProperty("2","小马");
properties.setProperty("3","小马");
FileWriter fileWriter = new FileWriter("prop.properties");
//comments :第一行的注释的内容
properties.store(fileWriter,"save data");
fileWriter.close();
}
/**
* 读取properties文件
*/
@Test
public void demo1() throws Exception {
Properties properties = new Properties();
FileReader fileReader = new FileReader("prop.properties");
properties.load(fileReader);
System.out.println(properties);
}
序列化
序列化:把对象写入磁盘
对象要实现Serializable
接口
public class Student implements Serializable {
private int id;
private String name;
private int age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
}
}
瞬态(transient)和静态(static)不能序列化
/**
* 序列化
* 把对象写入磁盘
*/
@Test
public void demo2() throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("prop.properties",true));
Student s1 = new Student(1, "小红", 18);
oos.writeObject(s1);
Student s2 = new Student(2, "小黄", 21);
oos.writeObject(s2);
oos.close();
}
反序列化:从磁盘获取对象
/**
* 反序列化
*/
@Test
public void demo3() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("prop.properties"));
Student o = (Student) ois.readObject();
System.out.println(o);
ois.close();
}
NIO
Buffers – 缓冲区 :针对系统的缓冲区
Channels – 通道 :类似于BIO里面的流
随机流RandomAccessFile
/**
* 文件切割
*/
@Test
public void demo5() throws Exception {
File file = new File("D:\\PeiXun\\新建文件夹\\demo.TS");
//创建随机流对象
RandomAccessFile raf = new RandomAccessFile(file, "rw");
//切割几份
int i =3;
//文件的大小
long length = file.length();
//除了最后一份的其他碎片的大小
long l = length / 3;
//设置指针位置
int pointerPosition =0;
raf.seek(pointerPosition);
//获取父级目录
String parent = file.getParent();
//获取字节输出流
FileOutputStream fos = null;
//byte[]
byte[] b;
for (int j = 1; j <=i; j++) {
fos = new FileOutputStream(parent + File.separator + "temp_" + j + ".TS");
if (j<i){//除了最后一份都进来
b=new byte[(int) l];
raf.read(b);
fos.write(b);
//指针后移
pointerPosition+=l;
raf.seek(pointerPosition);
}else{
//最后一份的长度等于总长度-指针的长度
b = new byte[(int) (length - pointerPosition)];
raf.read(b);
fos.write(b);
}
}
fos.close();
raf.close();
}