一、File类
File类是通过路径名定位文件和文件夹的,new File的时候,传入(String)、(String、String)、(File、String),能实现创建File对象。可以传入相对路径或绝对路径。再用对象createNewFile、mkdir、mkdirs来创建文件或文件夹;而删除操作则是通过delete方法来操作,删除的如果是文件则直接,如果是文件夹则需要空。
以上都是返回boolean来告知是否操作成功。
File类提供了一系列获取的方法:
getAbsolutePath();获取绝对路径、getName();获取文件或文件夹的名字、getParent();获取父路径、length();获取文件(文件夹无法获取准确的)大小、listFile();获取文件夹(不能文件)下的所有内容,可以搭配增强for遍历。
File类提供了一系列判断的方法:
isDirectory();判断是否为文件夹、isFile();判断是否文件、isExist();判读是否存在。都是返回boolean。
File file = new File("D:\\MyFileTest\\aaa");
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
if (file.getName().endsWith(".java")) {System.out.println(file);}
} else {
listJava(file);
}
}
二、字节流和字符流
所有的流对象,在结束使用时都需要调用.close()方法,结束本线程对该文件的使用,否则占用着该文件其他线程无法使用之。
流对象分为字节流和字符流,字节流分为InputStream字节输入流、OutputStream字节输出流;字符流分为Reader字符输入流、Writer字符输出流,以上都是接口。
OutputStream字节输出流有接口:FileOutputStream,常用方法有write(int/byte[]);byte[]可以写成(byte[],int 开始的索引,int 写出的长度)将内容写入对应file文件中:
FileOutputStream fos = new FileOutputStream("study_day11\\abc\\1.txt");
fos.write(97);
fos.write(98);
byte[] bs = new byte[] {65, 66, 67, 68, 69};
fos.write(bs);
fos.write(bs, 2, 3);
fos.close();
write()的形参有:int、byte[]
InputStream字节输入流有接口:FileInputStream,常用方法有read(int/byte[]);括号中设置读取的字节数量,由于读到的是int,所以需要强转成char:
FileInputStream fis = new FileInputStream("study_day11\\abc\\3.txt");
int b = fis.read();
System.out.println((char) b);
//如果要循环读则:
int b;
while ((b = fis.read()) != -1) {System.out.println((char) b);}
fis.close();
字节输入流循环byte数组读本地写到程序:
FileInputStream fis = new FileInputStream("study_day11\\abc\\3.txt");
// 定义数组保存读取的内容 数组的长度实际应该写1024的整数倍,建议写1024 * 8
byte[] buf = new byte[3];
int len;
while ((len = fis.read(buf)) != -1) {System.out.println(new String(buf, 0, len));
}fis.close();
String和byte[]互转:
byte[]转String:new String(byte bytes[], int offset, int length)
String转成byte[]:String对象.getBytes()
Reader字符输入流有接口:FileReader,常用方法有read(int/byte[]);括号中设置读取的字节数量,由于读到的是int,所以需要强转成char:
FileReader fr = new FileReader("study_day11\\abc\\4.txt");
int ch;
while ((ch = fr.read()) != -1) {System.out.println((char) ch);}
fr.close();
字符输入流循环char数组读写:
FileReader fr = new FileReader("study_day11\\abc\\4.txt");
char[] chs = new char[3];
int len;
while ((len = fr.read(chs)) != -1) {System.out.println(new String(chs, 0 , len));}
fr.close();
Writer字节输出流有接口:FileWriter,常用方法有write(int/char[]/String);String和char[]可以写成(String a/char[] a,int 开始的索引,int 写出的长度)将内容写入对应file文件中:
FileWriter fw = new FileWriter("study_day11\\abc\\3.txt", true);
fw.write(97);
fw.write(“123”);
fw.close();
write()的形参有:int、char[]、String