文件操作与IO流
目录
磁盘操作
File类
简述
创建File对象
文件操作
获取文件信息
判断文件
删除文件
创建文件
Files工具类
字符操作
字节操作
IO流
IO流的概念
字节操作(字节流)
输入流
InputStream
1.实例化对象
2.读取
BufferedInputStream
输出流
FileOutputStream
1.实例化对象
2.写入
字符操作(字符流)
输出流
FileWriter
1 实例化对象
2 写入字符
BufferedWriter
输入流
Reader
1 实例化对象
2 读取字符
BufferedReader
properties
相关方法
properties与IO流结合
磁盘操作
File类
简述
java.io.File 类是java提供的针对磁盘中文件和目录对象的一个类。代表操作系统的文件(文件、文件夹)
创建File对象
File f1=new File("E:\\programming\\猿究院");
System.out.println(f1);//存在的文件路径
File f2=new File("E:\\programming\\猿究院\\资源\\HashSet源码分析.docx");
System.out.println(f2);//不存在的目录路径
File f3=new File("E:\\programming\\猿究院\\aaa");
System.out.println(f3);//不存在的文件路径
File f4=new File("E:\\programming\\猿究院\\aaa\\test.txt");
System.out.println(f4);
文件操作
获取文件信息
String str="文件名:%s 文件大小:%d 文件最后一次修改时间:%s\n";
//public String getName() 获取文件名称
//public long length() 获取文件长度(即:字节数---真实的大小)。不能获取目录的长度--仅表示当前操作系统为保存目录所涉及的长度。
//public long lastModified() 获取最后一次的修改时间,毫秒值
System.out.printf(str,f1.getName(),f1.length(),new Date(f1.lastModified()));
System.out.printf(str,f2.getName(),f2.length(),new Date(f2.lastModified()));
System.out.printf(str,f3.getName(),f3.length(),new Date(f3.lastModified()));
System.out.printf(str,f4.getName(),f4.length(),new Date(f4.lastModified()));
// public String getAbsolutePath():获取文件的绝对路径
// public String getPath() :获取路径,返回定义文件时使用的路径
// pulic String getCannoicalPath() 获取规范
// File f1=new File("E:\\programming\\猿究院"); // --传入一个String path路径
// File f1=new File("E:\\programming","猿究院"); // --传入两个路径,分别为父路径和子路径
File f1 = new File(new File("E:\\programming"), "猿究院"); // --传入两个路径,分别为父路径和子路径System.out.println("文件绝对路径:"+f1.getAbsoluteFile());
System.out.println("文件使用路径:"+f1.getPath());
System.out.println("文件规范路径:"+f1.getCanonicalPath());File f2=new File(".\\a.txt");
System.out.println("文件绝对路径:"+f2.getAbsoluteFile());
System.out.println("文件使用路径:"+f2.getPath());
System.out.println("文件规范路径:"+f2.getCanonicalPath());
//public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组---注意返回类型
File f1=new File("E:\\programming");
String[] names=f1.list();
System.out.println(Arrays.toString(names));//public File[] listFiles() :获取指定目录下的所有文件或者目录的File数组----返回时File
File[] files=f1.listFiles();
System.out.println(Arrays.toString(files));
判断文件
// public boolean exists() :判断是否存在// public boolean isDirectory():判断是否是目录// public boolean isFile() :判断是否是文件
//存在的文件和目录
File f1=new File("E:\\programming\\猿究院");
File f2=new File("E:\\programming\\猿究院\\资源\\HashSet源码分析.docx");
//不存在的文件和目录
File f3=new File("E:\\programming\\猿究院\\aaa");
File f4=new File("E:\\programming\\猿究院\\aaa\\test.txt");//判断是否存在
String str="【%s】是否存在? %s,是否是文件?%s 是否是目录%s \n";
System.out.printf(str,f1.getName(),f1.exists(),f1.isFile(),f1.isDirectory());
System.out.printf(str,f2.getName(),f2.exists(),f2.isFile(),f2.isDirectory());
System.out.printf(str,f3.getName(),f3.exists(),f3.isFile(),f3.isDirectory());
System.out.printf(str,f4.getName(),f4.exists(),f4.isFile(),f4.isDirectory());
File f1=new File("D:\\IOTest\\a.txt");
System.out.println("是否可读?"+f1.canRead());
System.out.println("是否可写?"+f1.canWrite());
System.out.println("是否隐藏?"+f1.isHidden());
删除文件
File f1=new File("D:\\IOTest\\b.txt");
File f2=new File("D:\\IOTest\\fileStudy");//删除文件时,要求文件必须存在才能进行删除
boolean b1=f1.delete();
System.out.println("f1是否删除成功?"+b1);//只能删除存在的空目录
boolean b2=f2.delete();
System.out.println("f2是否删除成功?"+b2);
创建文件
File f1=new File("D:\\IOTest\\b.txt");
File f2=new File("D:\\IOTest\\资料");
File f3=new File("D:\\IOTest\\aaa\\资料");//1.创建文件createNewFile(),文件路径存在,文件不存在的时候为true
boolean b1=f1.createNewFile();
System.out.println("创建f1对象是否成功?"+b1);//2.创建文件夹,当文件夹不存在,且父路径存在的时候就可以创建
boolean b2=f2.mkdir();
System.out.println("创建f2对象是否成功?"+b2);//3.创建文件夹,如果父路径不存在,则一并创建
boolean b3=f3.mkdirs();
System.out.println("创建f3对象是否成功?"+b3);
Files工具类
字符操作
//byte[] readAllBytes(Path path) 读取文件中的所有字节。
Path p1=new File("D:\\IOTest\\test.jpg").toPath();
byte[] bytes= Files.readAllBytes(p1);
System.out.println(Arrays.toString(bytes));//readAllLine(Path path) 按行读取指定路径中的内容
Path p2=new File("D:\\IOTest\\a.txt").toPath();
List<String> list= Files.readAllLines(p2);
System.out.println(list);// Path write(Path path, List<String> list) 写入字节到指定的内容
ArrayList<String> arrayList=new ArrayList<>();
for(int i=0;i<30;i++){arrayList.add(UUID.randomUUID().toString());
}
Files.write(p2,arrayList);// Path write(Path path, byte[] bytes) 写入字节到指定的路径
// StandardOpenOption.APPEND 追加,否则直接覆盖内容
byte[] bytes1="我就是太阳".getBytes();
Files.write(p2, bytes1, StandardOpenOption.APPEND);
字节操作
Path p1=new File("D:\\IOTest\\test.jpg").toPath();
byte[] bytes= Files.readAllBytes(p1);
System.out.println("读取结束");Files.write(new File("D:\\IOTest\\copy.jpg").toPath(), bytes);
System.out.println("写出结束");//StandardCopyOption.REPLACE_EXISTING,如果文件存在,直接覆盖
Files.copy(Paths.get("D:\\IOTest\\test.jpg"),new File("D:\\IOTest\\copy2.jpg").toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("复制结束");
IO流
IO流的概念
I 表示Input ,把硬件文件的数据读入到内存的过程,称之输入,负责读
O表示output ,把内存中的数据写出到硬盘文件的过程 称之输出 负责写
字节操作(字节流)
输入流
InputStream
注意路径,一定是一个文件路径,且路径必须存在,如果不存在,则出异常
1.实例化对象
//public FileInputStream(String name)
InputStream inputStream1 = new FileInputStream("D:\\IOTest\\a.txt");
System.out.println(inputStream1);//public FileInputStream(File file)
InputStream inputStream2 = new FileInputStream(new File("D:\\IOTest\\a.txt"));
System.out.println(inputStream2);
2.读取
InputStream inputStream1 = new FileInputStream("D:\\IOTest\\a.txt");//int read() 读取字节,一个字节一个字节读取,直至末尾返回-1
// int data1;
// while ((data1=inputStream1.read())!=-1){
// System.out.print((char)data1);
// }//int read(byte b[]) 每次读取N个直接,将字节放到字节数组中,读取到末尾返回值-1
byte[] bytes = new byte[4];
int length;
while ((length = inputStream1.read(bytes)) != -1) {System.out.println("读取到的长度为:" + length + " 读取的内容为:" + new String(bytes, 0, length));
}//public void close() 关闭资源,还是建议放到try...catch语句块当中
inputStream1.close();
BufferedInputStream
try (InputStream inputStream1 = new FileInputStream("D:\\IOTest\\a.txt");) {BufferedInputStream bis = new BufferedInputStream(inputStream1);byte[] bytes = new byte[4];int length;while ((length = bis.read(bytes)) != -1) {System.out.println("读取到的长度为:" + length + " 读取的内容为:" + new String(bytes, 0, length));}
} catch (IOException e) {e.printStackTrace();
}
输出流
1.输出流路径一定要是一个文件路径
2.输出流的文件对象可以不存在,但是父路径一定要存在
3.如果路径中有内容,会将原路径中的内容进行覆盖
FileOutputStream
1.实例化对象
//public FileOutputStream(String name)
OutputStream os = new FileOutputStream("D:\\IOTest\\b.txt");
System.out.println(os);//FileOutputStream(File file)
OutputStream os2 = new FileOutputStream(new File("D:\\IOTest\\b.txt"));
System.out.println(os2);//public FileOutputStream(File file, boolean append) 是否追加,默认为false
OutputStream os3 = new FileOutputStream(new File("D:\\IOTest\\b.txt"), true);
System.out.println(os3);
2.写入
try (OutputStream os = new FileOutputStream("D:\\IOTest\\b.txt")) {//public abstract void write(int b) 写入一个字节os.write(97);os.write(98);os.write(99);//public void write(byte b[]) 把这个字节数组中的所有数据写到关联的设备中(设备包括文件、网络或者其他任何地方)os.write("庆祝反法西斯战争胜利80周年".getBytes());//public void write(byte b[], int off, int len) 从指定下标开始,写出指定个字节信息os.write("abcdefghijkl".getBytes(), 1, 6);System.out.println("end");} catch (IOException e) {}
try(OutputStream os=new FileOutputStream("D:\\IOTest\\b.txt",true)) {//windows换行写 \r \n//linux 换行 \r//mac 换行 \nos.write('a'); //写出一个字节信息os.write("\r\n".getBytes()); //写出一个换行信息os.write("我本将心照明月".getBytes()); //写出一个字节数组信息//根据不同的系统获取换行符String str = System.lineSeparator();for (int i = 0; i < 5; i++) {os.write((UUID.randomUUID().toString().substring(0, 8) + str).getBytes());}
}catch (IOException e){e.printStackTrace();
}
字符操作(字符流)
输出流
FileWriter
1 实例化对象
// 覆盖写
//FileWriter(String fileName)
Writer writer1 = new FileWriter("D:\\IOTest\\b.txt");
System.out.println(writer1);Writer writer2 = new FileWriter(new File("D:\\IOTest\\c.txt"));
System.out.println(writer2);//FileWriter(String fileName, boolean append) 追加写
Writer writer3 = new FileWriter("D:\\IOTest\\b.txt",true);
System.out.println(writer3);Writer writer4 = new FileWriter(new File("D:\\IOTest\\c.txt"));
System.out.println(writer4);
2 写入字符
try {Writer writer1 = new FileWriter("D:\\IOTest\\b.txt");String separator=System.lineSeparator();writer1.write(separator);// write(int c) 写入一个字符writer1.write('你');writer1.write('好');writer1.write(separator);//write(char cbuf[]) 写出字符数组writer1.write("我本将心照明月".toCharArray());writer1.write(separator);//write(char cbuf[], int off, int len) 写出字符数组中指定下标的元素writer1.write("奈何明月照沟渠".toCharArray(),4,3);writer1.write(separator);//write(String str) 写出字符串writer1.write("我就是太阳");writer1.write(separator);//write(String str, int off, int len) 写出字符串中指定下标的元素writer1.write("我,世界的法则",2,5);writer1.flush();System.out.println("end");} catch (IOException e) {e.printStackTrace();}
BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\IOTest\\c.txt"));){bw.write("Hello World");bw.newLine(); //换行bw.write("白日依山尽",0,3);
} catch (IOException e) {e.printStackTrace();
}
输入流
Reader
1 实例化对象
Reader r1 = new FileReader("D:\\IOTest\\b.txt");
System.out.println(r1);Reader r2 = new FileReader(new File("D:\\IOTest\\b.txt"));
System.out.println(r2);
2 读取字符
try(Reader reader = new FileReader("D:\\IOTest\\c.txt")) {//int read() 读取单个字符,返回字符对应的码表值,当为-1,读取结束
// int data;
// while ((data = reader.read()) != -1) {
// System.out.print((char) data);
// }//int read(char cbuf[]) 读取数据存入char数组中,返回读取的长度,如果没有数据返回-1char[] buf = new char[4];int len;while ((len = reader.read(buf)) != -1) {System.out.print(new String(buf, 0, len));}}catch (IOException e) {e.printStackTrace();}
BufferedReader
try(BufferedReader br = new BufferedReader(new FileReader("D:\\IOTest\\c.txt"))){//String readLine() 按行读取,当读取到末尾时,返回值为nullString str;while ((str = br.readLine()) != null) {System.out.println(str);}System.out.println("end");
}catch (Exception e){e.printStackTrace();
}
properties
相关方法
//Object setProperty(String key, String value) 添加元素Properties prop = new Properties();prop.setProperty("姓名", "暮雪");prop.setProperty("年龄", "23");System.out.println(prop);//String getProperty(String key) 获取键对应的值String str=prop.getProperty("年龄");System.out.println(str);//String getProperty(String key, String defaultValue) 获取键对应的值,没有返回默认值String str2= prop.getProperty("性别","不知");System.out.println(str2);//Set<String> stringPropertyNames() 获取所有的键Set<String> keys = prop.stringPropertyNames();for(String key:keys){System.out.println(key+":"+prop.getProperty(key));
properties与IO流结合
Properties prop = new Properties();
Reader reader=new FileReader("a.txt");//将输入流获取到的所有信息传递给p1对象
prop.load(reader);
Set<String> keys = prop.stringPropertyNames();
for (String key : keys) {System.out.println(key + ":" + prop.getProperty(key));
}