常用 java I/O 工具集合
递归的列出一个目录下的所有文件,知识点 java File
// 递归的列出一个目录下的所有文件,知识点 java File
public static void listAllFiles(File dir){
if (dir == null || !dir.exists()){
return;
}
if (dir.isFile()){
System.out.println(dir.getName());
return;
}
for (File file: dir.listFiles()){
listAllFiles(file);
}
}
复制文件 src->dist
//复制文件 src->dist
public static void copyFile(String src, String dist) throws IOException{
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dist);
byte[] buffer = new byte[20 * 1024];
int cnt;
// read() 最多读取 buffer.length 个字节
// 返回的是实际读取的个数
// 返回 -1 的时候表示读到 eof,即文件尾
while ((cnt = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, cnt);
}
in.close();
out.close();
}
实现逐行输出文本文件的内容
//实现逐行输出文本文件的内容
public static void readFileContent(String filePath) throws IOException{
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
//装饰者模式使得BufferReader组合了一个Reader对象
//在调用BufferReader的close()方法时会去调用Reader的close()方法
//因此只需要执行一次close()方法
bufferedReader.close();
}
序列化
//序列化
/* 序列化的类需要实现 Serializable 接口,
它只是一个标准,没有任何方法需要实现,但是
如果不去实现它的话而进行序列化,会抛出异常。*/
public static void serilizer() throws IOException, ClassNotFoundException{
A a1 = new A(123, "cs");
String objectFile = "file/a1";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
objectOutputStream.writeObject(a1);
System.out.println(objectOutputStream);
objectOutputStream.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
A a2 = (A)objectInputStream.readObject();
objectInputStream.close();
System.out.println(a2);
}
private static class A implements Serializable{
private int x;
private String y;
A(int x, String y){
this.x = x;
this.y = y;
}
@Override
public String toString(){
return "x= "+x + "y= "+ y;
}
}
URL 直接在URL中读取字节流数据
// URL 直接在URL中读取字节流数据
public static void readBytesFromURL(String url) throws IOException{
URL readUrl = new URL(url);
//字节流
InputStream is = readUrl.openStream();
//字符流
InputStreamReader isr = new InputStreamReader(is);
//提供缓存
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine())!= null){
System.out.println(line);
}
br.close();
}
//利用NIO快速读写文件
public static void fastCopyFile(String src, String dist) throws IOException{
//建立输入字节流
FileInputStream fis = new FileInputStream(src);
//获取输入文件的输入通道
FileChannel fcin = fis.getChannel();
//获取输出文件的字节流
FileOutputStream fos = new FileOutputStream(dist);
//获取输出文件的输出通道
FileChannel fout = fos.getChannel();
//建立1024字节的缓存区
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (true){
//从输入通道中读取数据到缓存区
int r = fcin.read(buffer);
if (r == -1) {
break;
}
//切换读->写
buffer.flip();
//把缓冲区的数据写到输出通道中
fout.write(buffer);
//最后清空缓冲区
buffer.clear();
}
}