@EggGump
2018-08-25T12:55:41.000000Z
字数 2297
阅读 574
java
1、File
File file = new File("d:/java/word.txt") ;if(file.exists() && !file.isDirectory()) {System.out.println(file.getName() + file.isHidden());file.delete() ;}else {file.createNewFile() ;}
2、FileInputStream FileOutputStream
针对字节流,读写汉字时有可能出现乱码。需要借助byte数组进行输入输出操作。
File file = new File("d:/java/word.txt") ;FileOutputStream fos = new FileOutputStream(file) ;byte text[] = "东北大学".getBytes() ;fos.write(text);fos.close() ;FileInputStream fis = new FileInputStream(file); ;text = new byte[1024] ;int len = fis.read(text) ;fis.close();System.out.println(new String(text,0,len)) ;
该方法是新建文件,如果文件本来存在,也是删除再新建
3、FileReader类和FIleWriter类(针对字符流。不需要借助byte数组来操作,对于输入流借助char数组
File file = new File("d:/java/word.txt") ;FileWriter out = new FileWriter(file) ;out.write("东北学");out.close();FileReader in = new FileReader(file) ;char[] text = new char[1024] ;int len = in.read(text) ;in.close();System.out.println(new String(text,0,len));
4、带缓存的输入输出流。缓存流为I/O流增加了内存缓冲区,是I/O的一种性能优化。BufferedInputStream与BufferedOutputStream
File file = new File("d:/java/word.txt") ;FileWriter fw = new FileWriter(file) ;BufferedWriter bw = new BufferedWriter(fw) ;bw.write("东北大学 没落了");bw.newLine();bw.write("日了狗了");bw.flush();fw.close();bw.close();FileReader fr = new FileReader(file) ;BufferedReader br = new BufferedReader(fr) ;String s = null ;while((s = br.readLine()) != null) {System.out.println(s) ;}fr.close();br.close();
5、数据输入输出流。当读取一个数据时,不必再关心这个数值应当是什么字节。DataInputStream与DataOutputStream类。
File file = new File("d:/java/word.txt") ;FileOutputStream fos = new FileOutputStream(file) ;DataOutputStream dos = new DataOutputStream(fos) ;dos.writeUTF("东北大学UTF") ;dos.writeChars("东北大学CHARS");dos.writeBytes("东北大学BTYES") ;fos.close();dos.close();FileInputStream fis = new FileInputStream(file) ;DataInputStream dis = new DataInputStream(fis) ;System.out.println(dis.readUTF()) ;fis.close();dis.close();
输出:东北大学UTF
6、压缩文件流
压缩:
File file = new File("d:/java/word.zip") ;ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file)) ;zos.putNextEntry(new ZipEntry("a/"));FileInputStream in = new FileInputStream(file) ;int b ;while((b = in.read()) != -1) {zos.write(b);}in.close();
结果:产生一个word.zip文件
解压:好吧,这个我没看懂是什么意思
File file = new File("d:/java/word.zip") ;ZipInputStream zis = new ZipInputStream(new FileInputStream(file)) ;ZipEntry entry ;while((entry=zis.getNextEntry()) != null&&!entry.isDirectory() ) {File file2 = new File(entry.getName()) ;if(!file.exists()) {file.createNewFile() ;zis.closeEntry();}}