File class and byte stream in IO stream
One, File class
1. Use recursion to output all files in a folder and all files in subfolders.
The code is as follows (example):
package com;
import org.junit.Test;
import java.io.File;
public class Test3 {
@Test
public void test3(){
File f= new File("D:\\新建文件夹\\day20-IO\\笔记");
File[] files=f.listFiles();
show(files);
}
public void show(File[] files){
for (File file :files){
if (file.isDirectory()){
System.out.println(file.getName()+": 是一个文件夹");
File[] imgs = file.listFiles();
show(imgs);
}else {
System.out.println(file.getName()+":是一个文件");
}
}
}
}
Two, byte stream
1. Byte input stream (read one byte at a time)
public static void main(String[] args) throws Exception {
//绝对路径
File f1 = new File("D:\\java培训\\java-day20\\src\\a.txt");
System.out.println(f1.exists());
//相对路径
File f2 = new File("src\\a.txt");
System.out.println(f2.exists());
//1.构建一条通往文件f2多的管道--流对象
FileInputStream fis = new FileInputStream(f2);
//2.调用方法
int l=fis.available();
for (int i = 0; i < l; i++) {
System.out.println(fis.read());
}
//关闭资源
fis.close();
}
2. Byte input stream (read multiple bytes at a time)
public static void main(String[] args) throws Exception {
//相对路径
File f1 = new File("src\\a.txt");
System.out.println(f1.length());
//1.构建一条通向文件f1的管道--流对象
FileInputStream fis = new FileInputStream(f1);
//2.调用方法--根据文件的字节长度,去构建一个相同长度的数组
byte[] bs = new byte[fis.available()];
//读取到文件中的字节数据,存入数组中,返回读到的实际字节个数
int r=fis.read(bs);
int r2=fis.read(bs);
System.out.println(Arrays.toString(bs));
System.out.println(r);
System.out.println(r2);
//关闭资源
fis.close();
}
3. Three ways to read and write
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("src\\a.txt");
FileOutputStream os = new FileOutputStream("src\\b.txt");
//方式1:
while (fis.available()>0){
os.write(fis.read());
}
//方式2:
int l=fis.available();
for (int i = 0; i < l; i++) {
os.write(fis.read());
}
//方式3:
int r=-1;
while ((r=fis.read())!=-1){
os.write(r);
}
}
Three, character stream
1. Character input stream
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("src\\1.txt");
char[] c=new char[6];
//方式一
while (fr.read(c)!=-1){
System.out.println(c);
}
//方式二
while (fr.read(c,0,6)!=-1){
System.out.println(c);
}
//方式三
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
System.out.print((char) fr.read());
}
System.out.println();
}
}
2. Character output stream
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("src\\test1.txt");
String str="昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否,知否?应是绿肥红瘦。";
fw.write(str);
fw.flush();
fw.close();
}
to sum up
The above is the content related to the File class, byte stream and character stream methods in the IO stream, mainly explaining their usage and some methods.