@Test
public void test1(){
//构造器1
File file1 = new File("hello.txt");//相对于当前module
File file2 = new File("D:\\src\\file\\he.txt");
System.out.println(file1);
System.out.println(file2);
//构造器2
File file3 = new File("D:\\Java自学\\IO流","src");
System.out.println(file3);
//构造器3
File file4 = new File(file3,"file");
System.out.println(file4);
}
String getAbsolutePath():获取绝对路径
String getPath():获取路径
String getName():获取名称
String getParent():获取上层文件目录路径。若无,返回null
long length():获取文件长度(字节数),不能获取目录的长度
long lastModified():获取最后一次的修改时间(毫秒值)
如下的两个方法适用于文件目录:
String[] list():获取指定目录下的所有文件或者文件目录的名称数组
File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组
@Test
public void test2(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO流");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParent());
System.out.println(file1.length());
System.out.println(new Date(file1.lastModified()));
System.out.println();
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getPath());
System.out.println(file2.getName());
System.out.println(file2.getParent());
System.out.println(file2.length());
System.out.println(file2.lastModified());
}
@Test
public void test3(){
File file = new File("D:\\Java");
String[] list = file.list();
for (String s : list) {
System.out.println(s);
}
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
}
}
boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)
要想保证返回true,需要file1在硬盘中存在,file2不能在硬盘中存在
@Test
public void test4(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO流\\world.txt");
boolean renameTo = file2.renameTo(file1);
System.out.println(renameTo);
}
boolean isDirectory():判断是否是文件目录
boolean isFile():判断是否是文件
boolean exists():判断是否存在
boolean canRead():判断是否可读
boolean canWrite():判断是否可写
boolean isHidden():判断是否隐藏
@Test
public void test5(){
File file1 = new File("hello.txt");
file1 = new File("Hello1.txt");
System.out.println(file1.isDirectory());
System.out.println(file1.isFile());
System.out.println(file1.exists());
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file1.isHidden());
System.out.println();
File file2 = new File("D:\\Java");
System.out.println(file2.isDirectory());
System.out.println(file2.isFile());
System.out.println(file2.exists());
System.out.println(file2.canRead());
System.out.println(file2.canWrite());
System.out.println(file2.isHidden());
}
创建硬盘中对应的文件或文件目录
boolean createNewFile():创建文件。若文件存在,则不存在,返回false
boolean mkdir():创建文件目录。如果此文件目录存在,则不创建。如果文件的上层目录不存在,则不创建
boolean mkdirs():创建文件目录。如果上层文件目录不存在,一并创建
删除硬盘中的文件或文件目录
boolean delete():删除文件或文件目录
Java中的删除不走回收站
@Test
public void test6() throws IOException {
//文件的创建
File file1 = new File("hi.txt");
if (!file1.exists()){
file1.createNewFile();
System.out.println("创建成功");
}else {//文件存在
file1.delete();
System.out.println("删除成功");
}
}
@Test
public void test7(){
//文件目录的创建
File file1 = new File("D:\\111");
boolean mkdir = file1.mkdir();
if (mkdir){
System.out.println("创建成功1");
}
File file2 = new File("D:\\222");
boolean mkdir1 = file2.mkdirs();
if (mkdir1){
System.out.println("创建成功2");
}
//文件目录的删除
//要想删除成功,MyDir文件必须为空文件夹
File file3 = new File("D:\\MyDir");
boolean delete = file3.delete();
if (delete){
System.out.println("删除成功");
}
}
| 抽象基类 | 字节流 | 字符流 |
|---|---|---|
| 输入流 | InputStream | Reader |
| 输出流 | OutputStream | Writer |
| 分类 | 字节输入流 | 字节输出流 | 字符输入流 | 字符输出流 |
|---|---|---|---|---|
| 抽象基类 | InputStream | OutputStream | Reader | Writer |
| 访问文件 | FileInputStream | FileOutputStream | FileReader | FileWriter |
| 访问数组 | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | CharArrayWriter |
| 访问管道 | PipedInputStream | PipedOutputStream | PipedReader | PipedWriter |
| 访问字符串 | StringReader | StringWriter | ||
| 缓冲流 | BufferedInputStream | BufferedOutputStream | BufferedReader | BufferedWriter |
| 转换流 | InputStreamReader | OutputStreamWriter | ||
| 对象流 | ObjectInputStream | ObjectOutputStream | ||
| FilterInputStream | FilterOutputStream | FilterReader | FilterWriter | |
| 打印流 | PrintStream | PrintWriter | ||
| 推回输入流 | PushbackInputStream | PushbackReader | ||
| 特殊流 | DataInputStream | DataOutputStream |
在整个IO流部分,大致的操作都可概括为以下4个步骤:
- 实例化File类对象
- 提供具体的流
- 数据的操作
- 流的关闭
read()方法:
write()方法:
public class FileReaderWriterTest {
/*
将当前module下的文件读入程序中,并输出到控制台
说明点:
1.read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
2.异常的处理:为了保证流资源一定可以执行关闭操作,需要用try-catch-finally处理
3.读入的文件一定要存在,否则就会报FileNotFoundException
*/
@Test
public void testFileReader(){
FileReader fr = null;
try {
//1.实例化File类对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前Module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
//方式一:
// int data = fr.read();
// while (data != -1){
// System.out.print((char)data);
// data = fr.read();//继续往下读
// }
//方式二:语法上针对于方式一的修改
int data;
while ((data = fr.read()) != -1){
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.流的关闭操作
if (fr != null) fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//对read()操作升级:使用read的重载方法
@Test
public void testFileReader1() {
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入到cbuf数组中字符的个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1){
//方式一:
//错误写法
// for (int i=0;i
// System.out.print(cbuf[i]);
// }
// for (int i=0; i < len; i++){
// System.out.print(cbuf[i]);
// }
//方式二:
//错误的写法,对应着方式一的错误的写法
// String str = new String(cbuf);
// System.out.print(str);
//正确的写法
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.资源的关闭
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*从内存中写出数据到硬盘的文件里。
说明:
1.输出操作:对应的File可以不存在,并不会报异常。
2.File对应硬盘中的文件:
如果不存在:在输出的过程中,会自动创建此文件。
如果存在:
如果流使用的构造器是:FileWriter(file,false)/fileWriter(file):对原有文件的覆盖
如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件后追加内容
*/
@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1.提供File类的对象
File file = new File("hello1.txt");
//2.提供FileWriter类的对象,用于数据的写出
fw = new FileWriter(file);
//3.写出的操作
fw.write("I have a dream!\n");
fw.write("You need to have a dream!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流资源的关闭
try {
if (fw !=null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testFileReaderFileWriter() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
//不能用字符流来处理图片等字节数据
// File srcFile = new File("XXX.jpg");
// File destFile = new File("XXX1.jpg");
//2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf数组中的字符的个数
while ((len = fr.read(cbuf))!=-1){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.关闭流资源
if (fw!=null)
fw.close();
if (fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.zeta.io;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 测试FileInputStream和FileOutputStream的使用
*
* 结论:
* 1.对于文本文件(.txt, .java, .c, .cpp),使用字符流处理
* 2.对于非文本文件(.jpg, .mp3, .mp4, .avi, .ppt, .doc...),使用字节流处理
* @author zeta
* @date 2022/7/24 - 10:31
*/
public class FileInputOutputStreamTest {
//使用字节流FileInputStream处理文本文件,可能出现乱码。
@Test
public void testFileInputStream() {
FileInputStream fis = null;
try {
//1.造文件
File file = new File("hello.txt");
//2.造流
fis = new FileInputStream(file);
//3.读数据
byte[] buffer = new byte[5];
int len;//记录每次读取字节的个数
while ((len = fis.read(buffer)) != -1){
String str = new String(buffer, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis!=null)
//4.关闭流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
实现对图片的复制操作
*/
@Test
public void testFileInputOutputStream() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//造File
File srcFile = new File("x.jpg");
File destFile = new File("x1.jpg");
//造流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//复制的过程
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭资源
if (fos!=null)fos.close();
if (fis!=null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//实现指定路径下文件的复制操作
public void copyFile(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//造File
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//造流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//复制的过程
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭资源
if (fos!=null)fos.close();
if (fis!=null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testCopyFile(){
long start = System.currentTimeMillis();
String srcPath = "xxx";
String destPath = "xxx2";
//可以复制文本文件
// srcPath = "hello.txt";
// destPath = "hello3.txt";
copyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:"+(end-start));//byte[5]复制操作花费的时间为:121907ms(2分钟)
//byte[1024]复制操作花费的时间为:879ms
}
}
处理流之一:缓冲流。
方法
BufferedInputStream (read(byte[] buffer))
BufferedOutputStream (write(byte[] buffer,0,len))
BufferedReader (read(char[] cbuf) / readLine())
BufferedWriter (write(char[] cubf,0,len)) / flush()
提高流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区
package com.zeta.io;
import org.junit.Test;
import java.io.*;
/**
* 处理流之一:缓冲流的使用
* 1.缓冲流
* BufferedInputStream
* BufferedOutputStream
* BufferedReader
* BufferedWriter
*
* 2.作用:提高流的读取、写入的速度
* 提高读写速度的原因:内部提供了一个缓冲区
*
* 3.处理流,就是“套接”在已有的流的基础上。
* @author zeta
* @date 2022/7/24 - 11:20
*/
public class BufferedTest {
/*
实现非文本文件的复制
*/
@Test
public void BufferedStreamTest() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("q.jpg");
File destFile = new File("q2.jpg");
//2.造流
//2.1造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.关闭资源
//要求1:先关闭外层的流,再关闭内层的流
if (bos!=null) bos.close();
if (bis!=null) bis.close();
//说明:关闭外层流的同时,内层流也会自动关闭。关于内层流的关闭可以省略
// fos.close();
// fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//实现文件复制的方法
public void copyFileWithBuffered(String srcPath,String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[1024];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
// bos.flush();//刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.关闭资源
//要求1:先关闭外层的流,再关闭内层的流
if (bos!=null) bos.close();
if (bis!=null) bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testCopyFile(){
long start = System.currentTimeMillis();
String srcPath = "xxx";
String destPath = "xxx2";
copyFileWithBuffered(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:"+(end-start));
}
/*
使用BufferedReader和BufferedWriter复制文本文件
*/
@Test
public void testBufferedReaderBufferedWriter() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//创建文件和相应的流
br = new BufferedReader(new FileReader(new File("aaa.txt")));
bw = new BufferedWriter(new FileWriter(new File("aaa1.txt")));
//读写操作
//方式一:char[]数组
// char[] cbuf = new char[1024];
// int len;
// while ((len = br.read(cbuf))!=-1){
// bw.write(cbuf,0,len);
// // bw.flush();
// }
//方式二:String
String data;
while ((data=br.readLine())!=null){
//方法一:自己添加\n
// bw.write(data+"\n");//data中不包含换行符
//方法二:调用方法
bw.write(data);
bw.newLine();//提供换行的操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
try {
if (bw!=null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br!=null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
处理流之二:转换流
转换流:属于字符流
InputStreamReader:将一个字节的输入流转换为字符的输入流
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
作用:提供字节流与字符流之间的转换
转换与编码解码的对应关系
解码:字节、字节数组 —> 字符数组、字符串
编码:字符数组、字符串 —> 字节、字节数组
字符集
ASCII码、GB2312、GBK、Unicode、UTF-8
package com.zeta.io;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 处理流之二:转换流的使用
* 1.转换流:属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
* 2.提供字节流与字符流之间的转换
*
* 3. 解码:字节、字节数组 ---> 字符数组、字符串
* 编码:字符数组、字符串 ---> 字节、字节数组
* 4.字符集
* ASCII码、GB2312、GBK、Unicode、UTF-8
*
* @author zeta
* @date 2022/7/25 - 21:30
*/
public class InputStreamReaderTest {
/*
此时处理异常仍然应该使用try-catch-finally
InputStreamReader的使用:实现字节的输入流到字符的输入流的转换
*/
@Test
public void test1() throws Exception{
FileInputStream fis = new FileInputStream("xxx.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
//参数2指明了字符集,具体使用哪个字符集取决于文件编码时使用的字符集
InputStreamReader isr = new InputStreamReader(fis, "UTF_8");//自定义使用的字符集
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf))!=-1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
/*
此时处理异常仍然应该使用try-catch-finally
综合使用InputStreamReader和OutputStreamWriter
*/
@Test
public void test2()throws Exception{
//造文件,造流
File file1 = new File("xxx.txt");
File file2 = new File("xxx1.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//读写过程
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf))!=-1){
osw.write(cbuf,0,len);
}
//关闭资源
osw.close();
isr.close();
}
}
分类
System.in:标准的输入流、默认从键盘输入
System.out:标准的输出流、默认从控制台输出
设置in和out
System类的setIn(InputStream is)/setOut(PrintStream ps)方式重新指定输入和输出的流
/*
练习
从键盘输入字符串,要求将读取到的整行字符串转换成大写输出。然后继续进行输入操作。
直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现 System.in ---> 转换流 ---->BufferedReader的readLine()
*/
public static void main(String[] args){
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true) {
System.out.println("请输入字符串:");
String data = br.readLine();
if ("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
System.out.println("程序结束");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br!=null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
分类
PrintStream 和 PrintWriter
打印流提供了一系列重载的print()和println()方法,比如常用的System.out.println()语句。
@Test
public void test2(){
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("text.txt"));
//创建打印输出流,设置为自动刷新模式(写入换行符或字节"\n"时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps!=null){//把标准输入输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i=0;i<255;i++){
System.out.print((char)i);
if (i%50==0) System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
ps.close();
}
}
分类
DataInputStream 和 DataOutputStream
作用
用于读取或写出基本数据类型的变量或字符串
/*
练习:将内存中的字符串、基本数据类型的变量写出到文件中
注意:处理异常仍然应该使用try-catch-finally.
*/
@Test
public void test3() throws IOException {
//1.造流和文件
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
//2.写
dos.writeUTF("Jack");
dos.flush();//刷新操作,将内存中已有的数据写入文件
dos.writeInt(20);
dos.flush();
dos.writeBoolean(true);
dos.flush();
//3.关闭
dos.close();
}
/*
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中
注意点:读取不同类型的数据类型的顺序要与当初写入文件时,保存的数据类型的顺序一致!
*/
@Test
public void test4() throws IOException {
//1.
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
//2.
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("isMale = " + isMale);
//3.
dis.close();
}
分类
ObjectInputStream 和 ObjectOutputStream
作用
用于存储和读取基本数据类型数据或对象的处理流。
它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
要求
要想一个java对象是可序列化的,需要满足相应的要求:
补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
序列化机制
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点;当其他程序获取了这种二进制流,就可以恢复成原来的Java对象。
Person类(实现了序列化)
package com.zeta.io.serializable;
import java.io.PrintStream;
import java.io.Serializable;
/**
* @author zeta
* @date 2022/7/27 - 17:05
*/
public class Person implements Serializable {
//序列版本号
public static final long serialVersionUID = 234354353523L;
private static String name;
private transient int age;
private Account acc;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, Account acc) {
this.name = name;
this.age = age;
this.acc = acc;
}
public Account getAcc() {
return acc;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", acc=" + acc +
'}';
}
public void setAcc(Account acc) {
this.acc = acc;
}
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;
}
}
class Account implements Serializable{
public static final long serialVersionUID = 258459852L;
private double balance;
public Account(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
'}';
}
}
测试类
package com.zeta.io.serializable;
import org.junit.Test;
import java.io.*;
/**
* @author zeta
* @date 2022/7/27 - 16:53
*/
public class ObjectStreamTest {
/*
序列化过程:将内存中的java对象保存在磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try {
//1.
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2.
oos.writeObject(new String("苏州科技大学"));
oos.flush();//刷新操作
oos.writeObject(new Person("Jack",21));
oos.flush();
oos.writeObject(new Person("Mark",22,new Account(1.1)));
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.
try {
if (oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
反序列化过程:将磁盘文件中的对象还原为内存中的java对象
使用ObjectInputStream实现
*/
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
//1.
ois = new ObjectInputStream(new FileInputStream("object.dat"));
//2.
Object obj = ois.readObject();
String str = (String)obj;
Person p1 = (Person) ois.readObject();
Person p2 = (Person) ois.readObject();
System.out.println(str);
System.out.println(p1);
System.out.println(p2);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//3.
try {
if (ois!=null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class RandomAccessFileTest {
@Test
public void test1() {
//1.
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("xxx.jpg"),"r");
raf2 = new RandomAccessFile(new File("xxx1.jpg"),"rw");
//2.
byte[] buffer = new byte[1024];
int len;
while((len=raf1.read(buffer))!=-1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.
try {
if (raf1!=null)
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (raf2!=null)
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test2() throws Exception{
RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"),"rw");
raf.seek(3);//指针调到3的位置
raf.write("xyz".getBytes());
raf.close();
}
/*
使用RandomAccessFile实现数据的插入效果
*/
@Test
public void test3() throws Exception{
RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"),"rw");
raf.seek(3);//指针调到3的位置
byte[] buffer = new byte[20];
//保存指针3后面的所有数据到StringBuilder中
StringBuilder builder = new StringBuilder((int)new File("hello.txt").length());//容量为文件长度
int len;
while ((len=raf.read(buffer))!=-1){
builder.append(new String(buffer,0,len));
}
//调回指针,写入"xyz"
raf.seek(3);
raf.write("xyz".getBytes());
//将StringBuilder中的数据写入文件中
raf.write(builder.toString().getBytes());
//关闭
raf.close();
//思考:将StringBuilder替换为ByteArrayOutputStream
}
}
NIO:New IO
JDK7新增加的类
Path类用来替换原始的File类
Paths和Files工具类提供了操作Path类的多种方法