文件基础知识:
创建文件的三种方法:
public static void create01(){ //根据路径创建一个file对象 String path="D:\\test01.txt"; File file01=new File(path); try { file01.createNewFile(); System.out.println("成功创建"); } catch (IOException e) { throw new RuntimeException(e); } }
public static void create02(){ //根据父目录文件+子路径创建一个file对象 File parent_file=new File("D:\\"); String path="test02.txt"; File file=new File(parent_file,path); try { file.createNewFile(); System.out.println("成功创建"); } catch (IOException e) { throw new RuntimeException(e); } }
public static void create03(){ //根据父目录+子路径创建一个file对象 String parent="D:\\"; String path="test03.txt"; File file=new File(parent,path); try { file.createNewFile(); System.out.println("成功创建"); } catch (IOException e) { throw new RuntimeException(e); } }
获取文件信息:
getName() 文件名
getAbsolutePath() 绝对路径
getParent() 父级目录
length() 文件大小【字节】
exists() 是否存在
isFile() 是否为文件
isDirectory() 是否为目录
delete() 删除文件【目录也是一种文件,也能用delete()删除】
mkdir() 创建一级目录
mkdirs() 创建多级目录
public static void create_dirs(){ String dir_path="D:\\a\\b\\c"; File file=new File(dir_path); if(file.exists()){ System.out.println("目录已存在"); }else{ if(file.mkdirs()){ System.out.println(dir_path+"创建成功"); }else{ System.out.println(dir_path+"创建失败"); } } }
IO流原理及分类:
JAVA IO流原理:
- I/O是input/output的缩写,I/O技术用于处理数据的传输,如读/写文件、网络通讯等。
- Java中,对于数据的输入/输出操作是以“流(stream)”的方式进行的。
- 在java.io包下提供了各种“流”类和接口。
- 输入input:读取外部数据(磁盘、光盘等)到程序(内存)中。
- 输出output:将程序(内存)中的数据输出到磁盘、光盘等存储设备中。
流的分类:
- 按操作数据单位不同分为:字节流(8 bit)二进制文件【InputStream / OutputStream】, 字符流(按字符)文本文件 【Reader / Writer】
- 按数据流的流向不同分为:输入流, 输出流
- 按流的角色不同分为:节点流, 处理流/包装流
常用的类:
InputStream(字节输入流):
常用子类:
- FileInputStream(文件输入流)
- BufferedInputStream(缓冲字节输入流)
- ObjectInputStream(对象字节输入流)
//单个字节的读取,效率比较低
public static void read01(){ String path="D:\\hello.txt"; FileInputStream fileInputStream=null; int res=0; try { fileInputStream=new FileInputStream(path); //以这种方法读取汉字的时候会出现乱码 //因为这是一个字节一个字节读的,而在UTF-8编码中一个汉字是3个字节,以这种方法读取时,会只读取到一个汉字的第一个字节的内容 while((res=fileInputStream.read())!=-1){ System.out.print((char)res); } } catch (IOException e) { e.printStackTrace(); }finally{ try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void read02(){ String path="D:\\hello.txt"; FileInputStream fileInputStream=null; int res=0; byte[]data=new byte[8];//一次读取8个字节 try { fileInputStream=new FileInputStream(path); while((res=fileInputStream.read(data))!=-1){ System.out.print(new String(data,0,res)); } } catch (IOException e) { e.printStackTrace(); }finally{ try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void write01(){ String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\hello_write.txt"; FileOutputStream fileOutputStream=null; try { /** * fileOutputStream=new FileOutputStream(path); 会覆盖文件里原先写好的内容 * fileOutputStream=new FileOutputStream(path,true); 会让后写的内容追加到文件后面 */ fileOutputStream=new FileOutputStream(path); //写入一个字节 fileOutputStream.write('H'); //写入字符串 String str="HelloWorld"; fileOutputStream.write(str.getBytes()); fileOutputStream.write(str.getBytes(),0,2); } catch (IOException e) { e.printStackTrace(); }finally { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
// 关于文件拷贝
public static void copy(){ String pre_path="D:\\file\\pic.jpg"; String now_path="D:\\file2\\pic_copy.jpg"; FileInputStream fileInputStream=null; FileOutputStream fileOutputStream=null; int readLen=0; try { fileInputStream=new FileInputStream(pre_path); byte[]data=new byte[1024]; fileOutputStream=new FileOutputStream(now_path); //一边读入,一边读出 while((readLen=fileInputStream.read(data))!=-1){ fileOutputStream.write(data,0,readLen); } System.out.println("拷贝成功"); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fileOutputStream!=null){ fileOutputStream.close(); } if(fileInputStream!=null){ fileInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
FileWriter / FileReader :
注意:FileWriter使用之后必须关闭(close)或者刷新(flush),否则写入不到指定的文件
public static void reader(){ String path="D:\\a_file.txt"; int data=0; FileReader fileReader=null; try { fileReader = new FileReader(path); while ((data = fileReader.read()) != -1) { System.out.print((char) data); } }catch (IOException e) { e.printStackTrace(); }finally { try{ fileReader.close(); }catch (IOException e){ e.printStackTrace(); } } }
public static void reader02(){ String path="D:\\a_file.txt"; int len=0; char[]data=new char[8]; FileReader fileReader=null; try { fileReader = new FileReader(path); while ((len = fileReader.read(data)) != -1) { System.out.print(new String(data,0,len)); } }catch (IOException e) { e.printStackTrace(); }finally { try{ fileReader.close(); }catch (IOException e){ e.printStackTrace(); } } }
public static void writer01(){ String path="D:\\b_file.txt"; FileWriter fileWriter=null; try { fileWriter=new FileWriter(path,true); //写单个字符 fileWriter.write('H'); //写入指定数组 char[]arr={'H','E','L','L','O'}; fileWriter.write(arr); //写入指定数组的指定部分 //从0位置开始写入长度为3的内容 fileWriter.write("你好,爪洼~".toCharArray(),0,3); //写入字符串 fileWriter.write("你好,爪洼~~~"); //写入字符串的指定位置 fileWriter.write("你好,爪洼~~~",0,2); } catch (IOException e) { e.printStackTrace(); }finally { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
BufferedWriter / BufferedReader ( 处理流 ):
有关键字Buffered,是一种处理流,为其包装的流增加了缓存功能,提高了输入输出的效率。
需要使用flush()才能将缓冲区中内容写入到实际的物理节点。但是,在现在版本的Java中,只需记得关闭输出流(调用close()方法),就会自动执行输出流的flush()方法,可以保证将缓冲区中内容写入。
public static void reader(){ String path="D:\\a_file.txt"; BufferedReader bufferedReader=null; //按行读取,效率高 String line; try { bufferedReader=new BufferedReader(new FileReader(path)); while((line=bufferedReader.readLine())!=null){ System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }finally{ try { //关闭时只需要关闭bufferedReader,因为底层会自动的关闭节点流 bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void writer() throws IOException { String path="D:\\c_file.txt"; BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(path,true)); bufferedWriter.write("hello"); //插入一个和系统相关的换行 bufferedWriter.newLine(); bufferedWriter.write("hello02"); bufferedWriter.newLine(); bufferedWriter.write("hello03"); bufferedWriter.close(); }
//关于文件拷贝 public static void copy(){ String path="D:\\a_file.txt"; String dest_path="D:\\a_file_copy.txt"; BufferedReader bufferedReader=null; BufferedWriter bufferedWriter=null; String line; try { bufferedReader=new BufferedReader(new FileReader(path)); bufferedWriter=new BufferedWriter(new FileWriter(dest_path)); while((line=bufferedReader.readLine())!=null){ //这里的读入一行不包括换行符,只是一行的内容 bufferedWriter.write(line); bufferedWriter.newLine(); } } catch (IOException e) { e.printStackTrace(); }finally { try { if (bufferedWriter != null) { bufferedWriter.close(); } if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } } }
//字节流处理图片、音乐的拷贝 public static void copy02(){ String path="D:\\pic.jpg"; String dest_path="D:\\pic02.jpg"; BufferedInputStream bufferedInputStream=null; BufferedOutputStream bufferedOutputStream=null; try { bufferedInputStream=new BufferedInputStream(new FileInputStream(path)); bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(dest_path)); byte[]data=new byte[1024]; int readLen=0; while((readLen=bufferedInputStream.read(data))!=-1){ bufferedOutputStream.write(data,0,readLen); } } catch (IOException e) { e.printStackTrace(); }finally { try { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
对象处理流:
ObjectOutputStream 提供了序列化功能
ObjectInputStream 提供了反序列化功能
关于序列化:
- 序列化是指把一个Java对象变成二进制内容,本质上就是一个byte[]数组。
- 序列化的作用:序列化后可以把byte[]保存到文件中,或者把byte[]通过网络传输到远程。
关于反序列化:
- 反序列化是指把一个二进制内容(也就是byte[]数组)变回Java对象。
- 有了反序列化,保存到文件中的byte[]数组又可以“变回”Java对象,或者从网络上读取byte[]并把它“变回”Java对象。
public class aboutObjectOutputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { //实现序列化 about_output(); //实现反序列化 about_input(); } public static void about_output() throws IOException{ String path="D:\\data.dat"; ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(path)); // int ->Integer (实现了Serializable) objectOutputStream.writeInt(100); // boolean -> Boolean (实现了Serializable) objectOutputStream.writeBoolean(true); // char ->Character (实现了Serializable) objectOutputStream.writeChar('a'); // double ->Double (实现了Serializable) objectOutputStream.writeDouble(9.5); // String objectOutputStream.writeUTF("你好,爪洼"); // 保存一个dog对象 objectOutputStream.writeObject(new Dog("狗",2)); objectOutputStream.close(); } public static void about_input() throws IOException, ClassNotFoundException { String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\data.dat"; ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(path)); // 读取的顺序必须和存入的数据的顺序一致 System.out.println(objectInputStream.readInt()); System.out.println(objectInputStream.readBoolean()); System.out.println(objectInputStream.readChar()); System.out.println(objectInputStream.readDouble()); System.out.println(objectInputStream.readUTF()); Object dog=objectInputStream.readObject(); System.out.println("狗的信息:"+dog); //调用Dog , 向下转型 Dog res_dog=(Dog) dog; System.out.println("狗名: "+res_dog.getName()); System.out.println("狗龄: "+res_dog.getAge()); objectInputStream.close(); } }
class Dog implements Serializable { private String name; private int age; public Dog(String name,int age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "{"+name+","+age+"}"; } }
转换流 (InputStreamReader / OutputStreamWriter):
InputStreamReader: Reader的子类,可以将 InputStream(字节流) 包装成(转换) Reader(字符流)
OutputStreamWriter: Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
当处理纯文本数据时,如果使用字符流效率就会更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
public class p11_InputStreamReader { public static void main(String[] args) throws IOException { String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\hello.txt"; // 1.把FileInputStream转化为InputStreamReader // 2.指定编码 utf-8 InputStreamReader isr=new InputStreamReader(new FileInputStream(path),"utf-8"); BufferedReader br=new BufferedReader(isr); String line=br.readLine(); System.out.println(line); br.close(); } }
public class p12_OutputStreamWriter { public static void main(String[] args) throws IOException { String path="D:\\二\\Example.SUEP\\C___IO\\src\\file\\special_write.txt"; OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(path),"gbk"); osw.write("读取并转换"); osw.close(); } }
标准输入输出流:
类型 默认设备
System.in 标准输入 InputStream 键盘
System.out 标准输出 PrintStream 显示器
打印流 (只有输出流,没有输入流):
printStream (字节流)
printWriter (字符流)
标签:file,JAVA,String,IOException,IO,new,path,public From: https://www.cnblogs.com/ztCoding/p/18212970