java.io.File类的使用
IO原理及流的分类
|---文件流 操作对象是文件
FileInputStream / FileOutputStream / FileReader / FileWriter
|---缓冲流 操作对象是内存
BufferedInputStream / BufferedOutputStream / BufferedReader / BufferedWriter
|--转换流
InputStramReader / OutputStreamWriter
File类
File 是一个文件或者一个目录
File能新建、删除、重命名文件和目录,但File不能访问文件内容本身,如果访问内容,需要io流。
File.separator 文件分隔符 \
/**
* 两种构造方法 区别不大
*/
File file = new File("E:\\abc\\tt.txt");
// 不常使用
File file1 = new File("E:\\abc", "tt\\txt");
File f3 = new File("E:\\e\\test\\ok");
f3.mkdirs();
try {
File f4 = new File(f3, "x.txt");
// 创建一个新文件 ;
f4.createNewFile();
if (f4.isFile()) {
System.out.println("F4是文件");
} else {
System.out.println("F4是文件夹");
}
} catch (IOException e) {
e.printStackTrace();
}
// 删除一个文件;
f3.delete();
递归
private static void digui(File file) {
if (file.isFile()) {
System.out.println(file.getAbsoluteFile() + "是文件");
} else {
System.out.println(file.getAbsoluteFile() + "是文件夹");
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
// if(file.isFile()){
// System.out.println(file.getAbsoluteFile() + "是文件");
// }else{
// System.out.println(file.getAbsoluteFile() + "是文件夹");
//// ...
// }
// }
//在这就开始递归了;
digui(f);
}
}
}
}
用来处理设备之间的数据传输,可以用输入/输出流(Stream)的方式进行。IO流

按数据单位分类: 字节流 Stram, 字符流(Reader/Writer)
按数据流向分类:输入流 ,输出流
按流的角色分类:节点流,处理流

文件字节输入流
try {
FileInputStream in = new FileInputStream("E:\\temp\\a.txt");
byte[] b = new byte[100];
int len = 0;
while ((len = in.read(b)) != -1) {
// 说明还没有读到最后 文件输入流,就是读文件, 写到 byte数组中
System.out.println(new String(b, 0, len));
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
文件字节输出流
private static void showFileOutputStream() {
try {
FileOutputStream out = new FileOutputStream("E:\\temp\\b.txt");
String content = "中华人民共和国万岁";
out.write(content.getBytes()); // 将内容写到内存中;
out.flush(); // 把内存中的数据刷写到硬盘
out.close(); // 关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
文件字节流很通用,可以用来操作任何类型的文件(图片,压缩包等),因为它使用的是二进制。
字符输入流
private static void showFileReader() {
try {
FileReader fr = new FileReader("E:\\temp\\a.txt");
char[] chars = new char[20];
int len = 0;
while ((len = fr.read(chars)) != -1) {
System.out.println(new String(chars, 0, len));
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符输出流
private static void showFileWriter(String text, String outPath) {
try {
FileWriter fw = new FileWriter(outPath);
fw.write(text);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论