1. I/O 流
分类:
节点流(或文件流)
FileInputStream/FileOutputStream/FileReader/FileWriter
缓冲流
BufferedInputStream/BufferedOutputStream
BufferedReader/BufferedWriter
转换流
InputStreamReader/OutputStreamWriter
打印流
PrintStream/PrintWriter
数据流
DataInputStream/DateOutputStream
对象流
ObjectInputStream/ObjectOutputStream
随机存取文件流
RamdomAccessFile
2.File 类
File类的一个对象,代表一个文件,或文件目录
File类、流相关的类,都定义在java.io包下。
File类对象,如果表示为一个文件,就可以理解为作为一个端点(起始点、目标点)被流所使用。代码上的体现:常常将File类的对象,作为参数传递给流的构造器中。
File类中提供了文件或文件目录的创建、重命名、长度检测、删除等操作,但是并没有涉及到文件内容的读写,如果涉及到文件内容的读写,就需要引入流的概念。
2.1实例化File。
String path = “路径”;
File file = new File(path);
2.2常用方法。
访问文件名:
getName():获取文件名
getPath():获取路径
getAbsoluteFile():获取路径
getAbsolutePath():获取路径
getParent():获取上层文件目录
renameTo(File newName):重命名。file.renameTo(file2) 想要返回true必须要求file存在,且file2不存在。
文件检测:
exists():存在性检测
canWrite():是否可写检测
canRead():是否可读检测
isFile():是否为文件检测
isDrectory():是否为目录检测
获取常规文件信息:
lastModified():最后修改时间
length():长度
文件操作相关:
createNewFile():创建新文件
delete():删除文件
目录操作相关:
mkdir():创建目录,上层如果存在,则不创建目录。
mkdirs():创建目录,上层如果存在,照样创建目录。
delete():删除目录。
list(): 返回当前目录下存在的所有文件路径或文件目录路径构成的数组。
listFiles():返回当前目录下存在的所有文件或文件目录构成的数组。
package fileTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
public class FileTest {
/**
* 文本文件复制
*/
@Test
public void testReaderWriter(){
File src = new File("hello.txt");
File dest = new File("dbcp1.txt");
FileReader reader = null;
FileWriter writer = null;
try {
//具体的读入、写出操作。
reader = new FileReader(src);
writer = new FileWriter(dest);
char[] cbuf = new char[20];
int len;//记录读入到cbuf中字符的个数。
while((len = reader.read(cbuf))!=-1)
writer.write(cbuf,0,len);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(writer != null)
writer.close();
if(reader!= null)
reader.close();
System.out.println("操作完成!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 非文本文件复制
*/
@Test
public void testFileInputOutputStream(){
// 1.提供原文件和目标文件
File src = new File("IMG_1537.JPG");
File dest = new File("COPY-IMG_1537.JPG");
// 2.创建相应的输入流和输出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
// 3.读取数据并写出数据的操作
byte[] buffer = new byte[1024];
int len ;//记录读入字节数组中的字节数
while((len = fis.read(buffer))!= -1){
fos.write(buffer,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
//从下往上找。
if(fos != null)
fos.close();
if(fis != null)
fis.close();
System.out.println("复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testFileOutputStream(){
//1.创建File类对象
File file = new File("abc.txt");
//2.创建FileOutputStream对象
FileOutputStream fos = null;
try {
// fos= new FileOutputStream(file);//如果文件存在,则覆盖文件。
fos= new FileOutputStream(file,true);//如果文件存在,则向文件中追加内容。
//3.写出数据的过程
//字符串--->字节数组
byte[] buffer = "\nI love China! I love BeiJing".getBytes();
fos.write(buffer);
fos.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testFileInputStream1(){
//1.创建File类的对象。
File file =new File("hello.txt");
FileInputStream fis = null ;
try {
//2.创建FileInputStream的对象。
fis = new FileInputStream(file);
//3.读取数据的操作
// 方式一:
// int data = fis.read();
// while(data != -1){
// System.out.print((char)data);
// data = fis.read();//读取文件的下一个字节或如果到达文件的末尾,返回-1
// }
// 方式二:优化版
// int data;
// while((data = fis.read()) != -1)
// System.out.print((char)data);
// 方式三:
int data;
byte[] buffer = new byte[5];
int len;//记录每次读入到buffer中的字节数
while((len = fis.read(buffer))!= -1){
// 错误处理:helloword123ld
// for(int i =0;i<buffer.length;i++)
// System.out.print((char)buffer[i]);
// 处理方式一:
// for(int i =0;i<len;i++)
// System.out.print((char)buffer[i]);
// 处理方式二:
String str = new String(buffer,0,len);
System.out.print(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fis == null){
return ;
}else{
//4.关闭流
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test(){
File file = new File("D:\\io\\hello.txt");
File file1 = new File("D:\\io1","hello.txt");
File file2 = new File("hello.txt");
}
}
package fileTest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
public class BufferedTest {
@Test
public void test(){
//1.创建文件
File src = new File("IMG_1537.JPG");
File dest = new File("IMG_1537_COPY.JPG");
//2.创建节点流
FileInputStream fis = null;
FileOutputStream fos = null;
//3.创建缓冲流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//4.读写操作
byte[] buffer = new byte[1024];
int len ;
while((len = bis.read(buffer)) != -1)
bos.write(buffer,0,len);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭资源:从外往里关闭
try {
if(bos != null)
bos.close();
if(bis != null)
bis.close();
//fos 和fis 的流关闭操作可以省略,在bos与bis的关闭中关闭了。
if(fos != null)
fos.close();
if(fis != null)
fis.close();
System.out.println("操作完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package fileTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.junit.Test;
public class StreamReaderWriterTest {
/**
* 解码测试
* @author DengDan E-mail: 1173922872@qq.com
* @version CreateTime:2018年10月8日下午7:15:00
*/
@Test
public void testInputStreamReader(){
File file = new File("hello.txt");
FileInputStream fis = null;
InputStreamReader isr = null ;
try {
fis = new FileInputStream(file);
isr= new InputStreamReader(fis, "UTf-8");//编码测试中,只要在OutputWriter(os,"charset")中设置编码集即可。
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf))!=-1)
System.out.println(new String(cbuf,0,len));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.流的分类
3.1抽象基类
字节流 | 字符流 | |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
3.2FileInputStream/FileOutputStream的使用:处理非文本文件(.jpg,.mp3,.doc)。
3.3FileReader/FileWriter的使用:处理文本文件。
package fileTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.junit.Test;
public class OutTest {
@Test
public void test(){
PrintStream ps = null;
File file = new File("D:\\OutTest.txt");
try{
FileOutputStream fos = new FileOutputStream(file);
//创建打印输出流,设置为自动刷新模式(写入换行符或字节'\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();
}
}
}
-
4.对象序列化机制
- 对象序列化机制允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网路节点。当其他程序获取了这种二进制流,就可以恢复成原来的java对象。
- 序列化的好处在于可以将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可以被还原。
- 序列化是RMI(Remote Method invoke ,远程方法调用)过程的参数和返回值都必须实现的机制,而RMI是JavaEE的基础。因此序列化机制是JavaEE平台的基础。
- 如果需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:Serializable/Externalizable。
package fileTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Test;
/**
* 对象流的使用 ObjectInputStream 和ObjectOutputStream
* 存储和读取基本数据类型或对象的处理流。
* 它的强大之处就是可以把Java中的对象写入数据源中,也能把对象从数据源中还原回来。
*/
public class ObjectInputOutputStream {
/**
* 2.反序列化过程:读取文件、通过网络传输过来--->还原为内存中的java对象。
*/
@Test
public void testObjectInputStream(){
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
String str1 = (String) ois.readObject();
String str2 = (String) ois.readObject();
System.out.println(str1);
System.out.println(str2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 1.序列化过程:内存中的java对象-->写入文件、通过网络传输出去
*/
@Test
public void testObjectOutputStream(){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
String str1 = new String("冬天来了,春天也就不远了。");
String str2 = new String("春天来了,夏天也就不远了。");
oos.writeObject(str1);
oos.flush();
oos.writeObject(str2);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}