IO操作
面试题
java中有几种类型的流?
字节流、字符流
字符流和字节流有什么区别?
字符流一般用于文本文件的写入和读取
字节流可以用于大部分文件,例如图片文件,文本文件等
字符流
谈谈Java IO里面的常见类,字节流、字符流、接口、实现类
1、IO简介
java I\O主要包括如下:
流式部分---最主要的部分。如:OutputStream、InputStream、Reader、Writer等
非流式部分----如File类、RandomAccessFile类和FileDescriptor等
I:input 输入 将文件的内容读取到内存中
O: output 输出 将内存中的内容写入文件中
用程序去控制文件和目录的文件的操作
例如:创建文件、目录、删除文件、目录。。。
java.io包最重要的5个类和1个接口File、OutputStream、InputStream、Writer、Reader类和Serializable接口
2、File类
File类(文件特征和文件管理):用于文件或目录的描述信息,例如生成新目录,修改文件名,删除文件,判断文件所在路径等。
文件和目录的抽象表示;
常用方法:
方法名及说明 | 返回值类型 |
---|---|
exists( ) 判断目录或文件是否存在 | boolean |
delete( ) 删除文件或目录 目录必须为空才能删除 | boolean |
isDirectory( ) 判断当前对象是否为目录 | boolean |
isFile( ) 判断当前对象是否为文件 | boolean |
mkdir( ) 创建当前对象路径的目录 | boolean |
mkdirs( ) 创建当前对象路径的目录,包含任何必需但不存在的目录。若操作失败,则可能已成功创建一些必需的父目录 | boolean |
createNewFile( ) 当且仅当该名称的文件不存在时,创建新的文件 | boolean |
list( ) 返回目录下所有的文件或目录列表组成的一个字符串数组 | String[] |
listFiles( ) 返回目录下所有的文件或目录列表组成的一个File对象数组 | File[] |
2.1、文件的操作
常用方法示例:
public static void main(String[] args)
{
//路径:要操作的文件或者目录的位置
String path="d:/xxx/xxx/xx.jpg";
File file=new File(path);
//判断是否存在
boolean result=file.exsits();
System.out.println(result);
//删除操作
//file.delete();
System.out.println("OK");
System.out.println("文件"+file.isFile());
System.out.println("目录"+file.isDirectory());
//FIle.separator 路径分割符
}
2.2、对目录和文件的操作
public static void main(String[] args)
{
String path="d:/aaa/a1/a2";
File dir=new File(path);
System.out.println(dir.isDirectory());
if(dir.exists())
{
System.out.println("已存在");
}
else{
dir.mkdirs();
System.out.println("OK");
}
for(int i=1;i<50;i++)
{
File file=new File(path+"/"+"test"+i+".txt");
try{
file.createNewFile();
System.out.println("OK");
}
catch(IOException e){
e.printStackTrace();
}
}
}
2.3、遍历文件
递归遍历某一文件夹下的所有文件:
public static void show(File file){
//判断是否是目录
if(file.isDirectory())
{
System.out.prinln("DIR:"+file.gatName());
//获取当前目录中的子项
File[] files=file.listFiles();
for(File file1:files)
{
//递归显示子项
show(file1);
}
}else
{
System.out.prinln("FILE:"+file.getName());
}
}
3、I//O流
InputStream字节流 二进制格式操作:抽象类,基于字节的输入操作,是所有输入流的父类,定义了所有输入流都具有的共同特征。
OutputStream字节流 二进制格式操作:抽象类,基于字节的输出操作,是所有输出流的父类。定义了所有输出流都具有的共同特征。
Reader(字符流,文本格式操作):抽象类,基于字符的输入操作。
Writer(字符流,文本格式操作):抽象类,基于字符的输出操作。
RandomAccessFile(随机文件操作):它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作。
按组成分为:字节流、字符流
字节流:以字节(byte)为单位构成的数据流,可以操作任意格式的文件;
字符流:以字符(字母、数字)为单位构成的数据流,主要操作文本文件;
按功能分:输入流、输出流
输入流:文件中读取数据--->内存(程序)
输出流:内存(程序)---->输入到文件中
IO:以流的方式进行读写;
jdk1.4之后:引入了NIO非阻塞式文件操作;
3.1 基于字节流进行读写操作
InputStream:
字节(8bit(位))输入流,抽象类依靠子类实现各种功能,二进制格式操作,用来从文件中读取数据到字节流;
InputStream是输入字节数据用的类,所以InputStream类提供了3种重载的read方法.Inputstream类中的常用方法:
-
public abstract int read( ):读取一个byte的数据,返回值是高位补0的int类型值。若返回值=-1说明没有读取到 任何字节读取工作结束。
-
public int read(byte b[ ]):读取b.length个字节的数据放到b数组中。返回值是读取的字节数。该方法实际上是 调用下一个方法实现的
-
public int read(byte b[ ], int off, int len):从输入流中多读取len个字节的数据,存放到偏移量为off的b数组 中。
-
public int available( ):返回输入流中可以读取的字节数。注意:若输入阻塞,当前线程将被挂起,如果 InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用,
-
public long skip(long n):忽略输入流中的n个字节,返回值是实际忽略的字节数, 跳过一些字节来读取 public int close( ) :使用完后,必须对我们打开的流进行关闭。
来看看几种不同的InputStream:
-
FileInputStream把一个文件作为InputStream,实现对文件的读取操作
-
ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用
-
StringBufferInputStream:把一个String对象作为InputStream
-
PipedInputStream:实现了pipe的概念,主要在线程中使用
-
SequenceInputStream:把多个InputStream合并为一个InputStream
FileInputStream:实现类
BufferedInputStream:带缓冲区的输入流
OutputStream
OutputStream提供了3个write方法来做数据的输出,这个是和InputStream是相对应的。
-
public void write(byte b[ ]):将参数b中的字节写到输出流。
-
public void write(byte b[ ], int off, int len) :将参数b的从偏移量off开始的len个字节写到输出流。
-
public abstract void write(int b) :先将int转换为byte类型,把低字节写入到输出流中。
-
public void flush( ) : 将数据缓冲区中数据全部输出,并清空缓冲区。
-
public void close( ) : 关闭输出流并释放与流相关的系统资源。
几种不同的OutputStream:
-
ByteArrayOutputStream:把信息存入内存中的一个缓冲区中
-
FileOutputStream:把信息存入文件中
-
PipedOutputStream:实现了pipe的概念,主要在线程中使用
-
SequenceOutputStream:把多个OutStream合并为一个OutStream
Reader和InputStream类似;Writer和OutputStream类似
FileOutputStream:实现类
BufferedOutputStream:带缓冲的输出流;
带缓冲区的IO流:
缓冲区:内存中的一块内存;
读取过程:磁盘文件--->缓冲区(内存)------->内存;
操作步骤:
1、初始化File对象
2、初始化InputStream/OutputStream/BufferedInputStream/BufferedOutStream对象
3、执行读read/写write操作
4、关闭释放资源
字节流读取、写入和复制文件
import java.io.*;
/**
* Description: 字节流读取写入以及复制文件
* Author: goature
* CreateDate: 2019/8/26 0026 20:13
* UpdateUser: goature
* UpdateDate: 2019/8/26 0026 20:13
* UpdateRemark: 修改内容
* Version: 1.0
*/
public class Test10 {
//文件的读取
public static void myinput(File file)
{
InputStream stream=null;
try {
stream=new FileInputStream(file);
byte[] data=new byte[1024];
int len=stream.read(data);
String str=new String(data,0,len);
System.out.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (stream!=null)
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//文件的写入
public static void myoutput(File file)
{
OutputStream stream=null;
try {
stream=new FileOutputStream(file);
stream.write("你好,你好,你好".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (stream!=null)
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//byte[] data=new byte[];
//
}
//利用BufferedInputStream带缓冲池读取文件
public static void mybufferedinput(File file)
{
BufferedInputStream inputStream=null;
try {
inputStream=new BufferedInputStream(new FileInputStream(file));
byte[] data=new byte[1024];
int len=inputStream.read(data);
String str=new String(data,0,len);
System.out.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//利用BufferedOutputStream带缓冲池写入文件
public static void mybufferedoutput(File file)
{
BufferedOutputStream outputStream=null;
try {
outputStream=new BufferedOutputStream(new FileOutputStream(file));
outputStream.write("assdfjljgkljg".getBytes());
System.out.println("OK");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (outputStream!=null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void mycopy(File sfile,File afile)
{
InputStream istream=null;
OutputStream ostream=null;
try {
istream=new FileInputStream(sfile);
ostream=new FileOutputStream(afile);
byte[] data=new byte[1024];
int len=istream.read(data);
ostream.write(data);
System.out.println("OK");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (ostream!=null)
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (istream!=null)
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
File file=new File("D:/test.txt");
Test10.myinput(file);
Test10.myoutput(file);
Test10.mybufferedoutput(file);
Test10.mybufferedinput(file);
Test10.mycopy(file,new File("D:/test12.txt"));
//Test10.myinput(file);
}
}
3.2 基于字符流进行读写操作
import java.io.*;
/**
* Description: 字符流写入读取文件
* Author: goature
* CreateDate: 2019/8/27 0027 9:23
* UpdateUser: goature
* UpdateDate: 2019/8/27 0027 9:23
* UpdateRemark: 修改内容
* Version: 1.0
*/
public class Test11 {
//字符流读取文件
public static void myreader(File file)
{
Reader reader=null;
try {
reader=new FileReader(file);
char[] data=new char[1024];
int len=reader.read(data);
String s=new String(data,0,len);
System.out.println(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (reader!=null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//字符流写入文件
public static void mywriter(File file)
{
Writer writer=null;
try {
writer=new FileWriter(file);
writer.write("哈哈哈哈哈哈哈哈哈哈哈");
writer.flush();
System.out.println("OK");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (writer!=null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//带缓冲池的读取文件
public static void mybufferedReader(File file)
{
BufferedReader reader=null;
String str;
try {
reader=new BufferedReader(new FileReader(file));
while ((str=reader.readLine())!=null)
{
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (reader!=null)
{
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//带缓冲池的写入文件
public static void mybufferedWriter(File file)
{
BufferedWriter writer=null;
String s;
try {
writer=new BufferedWriter(new FileWriter(file));
writer.write("aaaaaaaaaaaaaaaaaa");
writer.flush();
System.out.println("OK");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (writer!=null)
{
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
File file=new File("D:/test.txt");
Test11.mywriter(file);
Test11.myreader(file);
Test11.mybufferedWriter(file);
Test11.mybufferedReader(file);
}
}
3.3 字节流和字符流之间的转换
InputStreamReader:将读取的字节流转换成字符流
OutputStreamWriter:将写入的字节流转换成字符流
public static void main(String[] args)
{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File("路径"));
//输入字节流---->输入字符流
Reader read=new InputStreamReader(bis);
//输出字节流----->输出字符流
OutputStream opm=new FileOutputStream(new File("路径"));
Writer writer=new OutputStreamWriter(opm);
}
PrintWriter:格式化的输出流
public static void main(String[] args)
{
PrintWriter writer=null;
try{
writer=new PrintWriter(new File("路径"));
writer.println("仙人抚我顶");
writer.println("结发授长生");
System.out.println("OK");
}catch(FileNotFoundException e)
{
e.printStackTrace();
}finally{
if(writer!=null)
{
writer.close();
}
}
}
4、序列化和反序列化
该对象需要实现Serializable接口
序列化:将对象转成字节序列,输出到介质中的过程,输出操作;
反序列化:读取文件中的字节序列,直接转成对象的过程,读取操作;
序列化:
public static void main(String[] args)
{
//序列化
Role role=new Role("赵云",99,"战士");
String path="d:/role.bin";
ObjectOutputStream writer=null;
try{
writer=new ObjectOutputStream(new FileOutputStream(path));
//写入对象
writer.writeObject(role);
System.out.println("OK");
}catch(IOException e){
e.printStackTrace();
}finally
{
try{
if(writer!=null)
writer.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
反序列化:
public static void main(String[] args)
{
//反序列化
Role role=null;
String path="d:/role.bin";
ObjectInputStream reader=null;
try{
reader=new ObjectInputStream(new FileInputStream(path));
role=(Role)reader.readObject();
System.out.println(role);
System.out.println("OK");
}catch(IOException e)
{
e.printStackTrace();
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}finally
{
if(reader!=null)
reader.close();
}catch(IOException e)
{
e.printStackTrace();
}
}