IO流
-
输入流:数据从文件到程序(内存)的路径
-
输出流:数据从内存到文件的路径
-
流是文件的通道
-
文件的3种创建方式
public class a { public static void main(String[] args) { } @Test public void create01() { String filepath = "D:\\news1.txt"; File file = new File(filepath); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { e.printStackTrace(); } } //这里new了一个file,只是在java中的一个对象 //只有执行了createNewFile方法,才会真正的在磁盘中创建文件 @Test public void create02(){ File parentFile = new File("D:\\"); String fileName = "news2.txt"; File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("创建好了"); } catch (IOException e) { e.printStackTrace(); } } @Test public void create03(){ String parentPath = "D:\\"; String fileName = "news3.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("11111"); } catch (IOException e) { e.printStackTrace(); } } }
4.目录的操作(delete mkdirs创建多级目录 mkdir一级目录)
在java程序中,目录也是特殊的文件
删除目录的前提是目录为空 delete的用法
分类
-
按操作数据 单位不同分为: 字节流(8bit)二进制文件比如图片,视频,word,pdf等保证没有损坏,字符流(根据编码的不同)文本文件
-
流向不同分为 :输入流 输出流
-
流的角色不同分为 :节点流 处理流
-
字节输入和输出流: InputStream OutStream
字符输入和输出流: Reader 和Writer
这四个都是抽象类,只有通过new子类去实现实例化
InputStream
public class FileInputStream01 { public static void main(String[] args) { } @Test //read()是单个字节的读取 效率低 public void readFile01() { String filePath = "D:\\hello.txt"; int readData = 0; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filePath); while ((readData = fileInputStream.read()) != -1) { System.out.print((char) readData); } } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } @Test public void readFile02() { String filePath = "D:\\hello.txt"; int readLen = 0; //字节数组 byte[] buf = new byte[8];//一次读取8个字节 FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filePath); while ((readLen = fileInputStream.read(buf)) != -1) { System.out.print(new String(buf,0,readLen)); } } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
OutPutStream
public class OutPutStream01 { public static void main(String[] args) { } @Test public void writeFile(){ String filePath ="D:\\a.txt"; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(filePath); //fileOutputStream.write('H');//写一个字节 //写入字符串 str.getBytes()可以把字符串--->字节数组 //new FileOutputStream(filePath)这种创建方式 在里面写入内容时,会覆盖原来的内容 //new FileOutputStream(filePath,true)这种创建方式 在里面写入内容时,是追加到内容后面 String str = "hello,world"; fileOutputStream.write(str.getBytes()); } catch (IOException e) { e.printStackTrace(); }finally { try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
文件拷贝
public class FileCopy { public static void main(String[] args) { //创建文件的输入流 ,将文件读取到程序中去 //创建文件的输出流,将读取到的文件数据,写入到指定的文件 String filePath1 = "D:\\x.JPG"; String filePath2 = "D:\\xi.JPG"; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(filePath1); fileOutputStream = new FileOutputStream(filePath2); //定义一个字节数组,提高读取效果 byte[] buf= new byte[1024]; int readlen= 0; while((readlen =fileInputStream.read(buf))!=-1){ //读取到后就写进去 边读边写 fileOutputStream.write(buf,0,readlen); } System.out.println("拷贝成功"); } catch (IOException e) { throw new RuntimeException(e); }finally { if(fileInputStream!=null) { try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } if(fileOutputStream!=null) { try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }
FileReader
public class FileReader01 { public static void main(String[] args) { String filePath = "D:\\story.txt"; FileReader fileReader = null; int Data =0; try { fileReader = new FileReader(filePath); //循环读取 使用read,单个字符读取 while((Data = fileReader.read())!=-1){ System.out.print((char) Data); } } catch (IOException e) { throw new RuntimeException(e); }finally { if (fileReader !=null){ try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } @Test public void reader(){ //字符数组读取文件 String filePath = "D:\\story.txt"; FileReader fileReader = null; int readlen = 0; char[] buf =new char[8]; try { fileReader = new FileReader(filePath); //循环读取 read(buf),返回的是实际读取到的字符数 while((readlen = fileReader.read(buf))!=-1){ System.out.print(new String(buf,0,readlen)); } } catch (IOException e) { throw new RuntimeException(e); }finally { if (fileReader !=null){ try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }
FileWriter
public class FileWriter01 { //对于FileWriter,一定要关闭流,或者flush才能真正的把数据写到文件中 public static void main(String[] args) { String filePath = "D:\\note.txt"; FileWriter fileWriter = null; char[] chars ={'a','b','c'}; try { fileWriter = new FileWriter(filePath); //写入单个字符 write(int) fileWriter.write('H'); //写入指定数组 write(char[]) fileWriter.write(chars); //写入指定数组的指定部分 write(char[],off,len) fileWriter.write("杨倩楠的家".toCharArray(),0,4); //写入整个字符串 write(String) fileWriter.write(" 你好北京-"); //写入字符串的指定部分 write(string,off,len) fileWriter.write("上海tianjin",0,3); } catch (IOException e) { throw new RuntimeException(e); }finally { try { //fileWriter.flush();清空缓存就是刷新(将缓存的数据写入文件内) fileWriter.close();//关闭文件流= flush+关闭 } catch (IOException e) { throw new RuntimeException(e); } } } }
包装流(处理流)
BufferedReader /BufferedWriter
BufferedReader类中,有属性Reader,可以封装一个节点流,只要是任意的一个Reader子类
BufferedReader/bufferedWriter
public class BufferedReader01 { public static void main(String[] args ) { String filePath = "D:\\story.txt"; BufferedReader bufferedReader = null; //创建BufferedReader try { bufferedReader = new BufferedReader(new FileReader(filePath)); //读取 按行读取效率高 //bufferedReader.readLine() 返回null是,表示读取完毕 String line; while( (line = bufferedReader.readLine())!= null){ System.out.println(line); } } catch (IOException e) { throw new RuntimeException(e); }finally { try { bufferedReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } }
public class BufferedWriter01 { public static void main(String[] args) throws IOException { //new FileWriter(filePath) 以覆盖的方式写入 //new FileWriter(filePath,true) 以追加的方式写入 String filePath = "D:\\ok.txt"; BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); bufferedWriter.write("我爱你"); //插入一个和系统相关的行 bufferedWriter.newLine(); bufferedWriter.write("我爱你11111"); //关闭外层的流就可 new FileWriter(filePath),会在底层关闭 bufferedWriter.close(); } }
Buffered字节处理流 可以处理文本
public class BufferCopy02 { public static void main(String[] args) throws IOException{ String srcFilePath = "D:\\x.JPG"; String destFilePath = "D:\\x2.JPG"; BufferedInputStream bufferedInputStream=null; BufferedOutputStream bufferedOutputStream =null; bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFilePath)); bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFilePath)); //循环的读取文件,并写入到destFilePath byte[]buff = new byte[1024]; int readlen = 0; while((readlen =bufferedInputStream.read(buff))!=-1){ bufferedOutputStream.write(buff,0,readlen); } if(bufferedInputStream!=null){ bufferedInputStream.close(); } if(bufferedOutputStream!=null){ bufferedOutputStream.close(); } } }
对象处理流
-
序列化:在保存数据时,保存数据的值和数据类型 ObjectOuputStream
-
反序列化:在恢复数据的时候,恢复数据的值和数据类型ObjectInputStream
-
要让某个类可序列化 必须实现接口 之一:
Serializable //这是一个标记接口,没有方法
Externalizable //该接口有方法需要实现,一般不用
public class d { public static void main(String[] args) throws IOException, ClassNotFoundException { //指定反序列化文件 String filePath = "D:\\data.dat"; ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath)); //读取(反序列化)的顺序要和你保存数据(序列化)顺序一致 System.out.println(ois.readInt()); System.out.println(ois.readBoolean()); System.out.println(ois.readChar()); System.out.println(ois.readDouble()); System.out.println(ois.readUTF()); Object dog = ois.readObject(); System.out.println("运行类型"+dog.getClass()); System.out.println("信息"+dog); ois.close(); } }
-
使用细节
-
读写顺序要一致
-
要求序列化或反序列化的对象,需要是实现Serializable
-
序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
-
序列化对象时,默认将所有的属性都进行序列化,但除了static或transient修饰的成员
-
序列化对象时,要求里面属性的类型也需要实现序列化接口
-
序列化具有可继承性,也就i是如果某类实现了序列化,它的子类也默认实现序列化
标准输入输出流
public class a1 { public static void main(String[] args) { // System.in 编译类型 Inputstream // System.in 运行类型 BufferedInputstream //表示标准输入 键盘 System.out.println(System.in.getClass()); //System.out 编译类型 PrintStream //System.out 运行类型 PrintStream //表示标准输出 显示器 System.out.println(System.out.getClass()); } }
-
转换流(字节流-->字符流)
字节流可以指定一个编码方式
InputStreamReader
把FileInputStream转换成BufferedReader
public class e { public static void main(String[] args) throws IOException { String filePath = "D:\\a.txt"; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); String s = br.readLine(); System.out.println(s); br.close(); } }
OutputStreamWriter
public class e { public static void main(String[] args) throws IOException { String filePath = "D:\\yqn.txt"; String charSet ="utf8";//编码方式可以指定换成 gbk OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),charSet ); osw.write("hi,杨倩楠"); osw.close(); } }
打印流
只有输出流
PrintStream(字节打印流)
public class printstream_ { public static void main(String[] args) throws IOException { PrintStream out = System.out; //默认情况下,PrintStream的输出位置是标准输出,即显示器 out.print("hi,你好"); out.write("韩顺平,你好".getBytes());//因为print底层使用的是write,所以我们可以直接调用write进行打印/输出 out.close(); //我们可以去改变打印输出流的位置/设备 System.setOut(new PrintStream("D:\\f1.txt")); System.out.println("hello,你好呀!"); } }
PrintWrite(字符打印流)
public class printwriter_ { public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); pw.print("hello,你好"); ///改变输出位置 PrintWriter printWriter = new PrintWriter(new FileWriter("D:\\f2.txt")); printWriter.print("你好"); printWriter.close(); pw.close(); } }
Properties(专门用于读写配置文件的集合类)
配置文件的格式:
键=值
键值对不需要有空格,值不需要有引号,默认类型是String
传统方法
public class Properties01 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("D:\\diea2\\GUI2\\untitled\\src\\mysql.properties")); String line = ""; while( (line=br.readLine())!=null){ String[] split = line.split("="); //如果我们指定只输出ip的值 if("ip".equals(split[0])) { System.out.println(split[0] + split[1]); } } br.close(); } }
用propersties读文件
public class Properties02 { public static void main(String[] args) throws IOException { Properties pt = new Properties(); pt.load(new FileReader("D:\\diea2\\GUI2\\untitled\\src\\mysql.properties")); pt.list(System.out); String user = pt.getProperty("user"); String pwd = pt.getProperty("pwd"); System.out.println("用户名是"+user); System.out.println("密码是"+pwd); } }
用propersties修改文件
public class Properties03 { public static void main(String[] args) throws IOException { Properties properties = new Properties(); //创建 如果原来没有key 就是创建 如果原来有key 那就会修改 properties.setProperty("charset","utf8"); properties.setProperty("user","汤姆");//保存中文 是保存文字的unicode码值 properties.setProperty("pwd","123456"); //将k-v存储到文件中即可 properties.store(new FileOutputStream("D:\\diea2\\GUI2\\untitled\\src\\mysql.properties2"),"hello "); System.out.println("文件配置成功"); } }
1
public class f { public static void main(String[] args) throws IOException { String directoryPath = "D:\\mytemp"; File file = new File(directoryPath); if (!file.exists()) { //创建 if (file.mkdirs()) { System.out.println(directoryPath + "创建成功"); } else { System.out.println("创建失败"); } } String filePath = directoryPath + "\\hello.txt"; file = new File(filePath); if (!file.exists()) { //创建文件 if (file.createNewFile()) { System.out.println(filePath + "创建成功"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); bufferedWriter.write("hello world"); bufferedWriter.close(); } else { System.out.println("创建失败"); } }else { System.out.println(filePath+"文件已经存在,不要重复创建"); } } }
2
public class f { public static void main(String[] args) throws IOException { //用BufferedReader读取一个文本文件,为每行加上行号,连同内容一起显示到屏幕上 String filePath = "D:\\a.txt"; BufferedReader br = null; String line = ""; int linenum = 0; try { br= new BufferedReader(new FileReader(filePath)); while (( (line = br.readLine())!=null)){ System.out.println(++linenum + line); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if(br!=null){ br.close(); } } } }
3
public class f { public static void main(String[] args) throws IOException { String filePath = "D:\\diea2\\GUI2\\untitled\\src\\dog.properties"; Properties properties = new Properties(); properties.load(new FileReader(filePath)); String name = properties.get("name")+""; //object-->String 在后面加一个空的字符串 int age =Integer.parseInt( properties.get("age")+"");//object-->int Integer.parseInt()+"" String color = properties.get("color")+"";//object-->String 在后面加一个空的字符串 Dog dog = new Dog(name, age,color); System.out.println("dog信息====="); System.out.println(dog); //将创建的dog对象,序列化到 cch.txt文件中 String serfilePath = "D:\\cch.txt"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serfilePath)); oos.writeObject(dog); oos.close(); } //编写一个方法,反序列化回来 @Test public void m2() throws IOException, ClassNotFoundException { String filePath2 = "D:\\cch.txt"; ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath2)); Dog dog=(Dog) ois.readObject(); System.out.println(dog); ois.close(); } } class Dog implements Serializable{ private String name; private int age; private String color; public Dog(String name, int age, String color) { this.name = name; this.age = age; this.color = color; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + ", color='" + color + '\'' + '}'; } }