1 // 简单实现复制 2 public static void main(String[] args) throws IOException { 3 //1,读取一个已有的文本文件,使用字符读取流和文件相关联。 4 FileReader fr = new FileReader("IO流_2.txt"); 5 //2,创建一个目的,用于存储读到数据。 6 FileWriter fw = new FileWriter("copytext_1.txt"); 7 //3,频繁的读写操作。 8 int ch = 0; 9 while((ch=fr.read())!=-1){ 10 fw.write(ch); 11 } 12 //4,关闭流资源。 13 fw.close(); 14 fr.close(); 15 } 16 17 // 引入缓冲做复制优化 手动定义缓冲去 18 // 引入字符数组作为缓冲区:(循环次数小,效率高) 19 private static final int BUFFER_SIZE = 1024; 20 public static void main(String[] args) { 21 FileReader fr = null; 22 FileWriter fw = null; 23 try { 24 fr = new FileReader("IO流_2.txt"); 25 fw = new FileWriter("copytest_2.txt"); 26 //创建一个临时容器,用于缓存读取到的字符。 27 char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。 28 //定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数) 29 int len = 0; 30 while((len=fr.read(buf))!=-1){ 31 fw.write(buf, 0, len); 32 } 33 } catch (Exception e) { 34 // System.out.println("读写失败"); 35 throw new RuntimeException("读写失败"); 36 }finally{ 37 if(fw!=null) 38 try { 39 fw.close(); 40 } catch (IOException e) { 41 42 e.printStackTrace(); 43 } 44 if(fr!=null) 45 try { 46 fr.close(); 47 } catch (IOException e) { 48 49 e.printStackTrace(); 50 } 51 } 52 } 53 54 // 优化三:使用装饰者模式添加上缓冲区功能 55 public static void main(String[] args) throws IOException { 56 FileReader fr = new FileReader("buf.txt"); 57 // 装饰上缓冲区功能 58 BufferedReader bufr = new BufferedReader(fr); 59 60 FileWriter fw = new FileWriter("buf_copy.txt"); 61 BufferedWriter bufw = new BufferedWriter(fw); 62 63 String line = null; 64 while((line=bufr.readLine())!=null){ 65 bufw.write(line); 66 bufw.newLine(); 67 bufw.flush(); 68 } 69 /* 70 int ch = 0; 71 while((ch=bufr.read())!=-1){ 72 bufw.write(ch); 73 } 74 */ 75 bufw.close(); 76 bufr.close(); 77 }
InputStream input = new GZIPInputStream( // 第二层装饰 new BufferedInputStream( // 第一层装饰 new FileInputStream("test.gz") // 核心功能 ));
// 压缩 ByteArrayOutputStream out = new ByteArrayOutputStream(); gzip = new GZIPOutputStream(out); gzip.write(str.getBytes(encoding)); // 解压缩 byte[] uncompress(byte[] bytes) { if (bytes == null || bytes.length == 0) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); try { GZIPInputStream ungzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = ungzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } } catch (IOException e) { ApiLogger.error("gzip uncompress error.", e); } return out.toByteArray(); }
new File("/usr/bin/javac"); // Windows平台使用\作为路径分隔符,在Java字符串中需要用\\表示一个\。Linux平台使用/作为路径分隔符: // 传先对路径,假设当前java文件目录是C:\Docs File f1 = new File("sub\\javac"); // 绝对路径是C:\Docs\sub\javac File f3 = new File(".\\sub\\javac"); // 绝对路径是C:\Docs\sub\javac File f3 = new File("..\\sub\\javac"); // 绝对路径是C:\sub\javac
int n; n = input.read(); // 必须等待read()方法返回才能执行下一行代码 int m = n
public static void main(String[] args) throws IOException { byte[] data = { 72, 101, 108, 108, 111, 33 }; try (InputStream input = new ByteArrayInputStream(data)) { int n; while ((n = input.read()) != -1) { System.out.println((char)n); } } }
// write()方法也是阻塞 OutputStream output = new FileOutputStream("out/readme.txt"); output.write("Hello".getBytes("UTF-8")); // Hello output.close();
BufferedFileInputStream extends FileInputStream DigestFileInputStream extends FileInputStream CipherFileInputStream extends FileInputStream
// 如果资源文件不存在,input则为null try (InputStream input = getClass().getResourceAsStream("/default.properties")) { if (input != null) { // TODO: } }
Properties props = new Properties(); props.load(inputStreamFromClassPath("/default.properties")); props.load(inputStreamFromFile("./conf.properties"));
static <T extends Serializable> T clone(T obj) { T cloneObj = null; try { // 写入字节流 ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bo); oos.writeObject(obj); oos.close(); // 分配内存,写入原始对象,生成新对象 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());//获取上面的输出字节流 ObjectInputStream oi = new ObjectInputStream(bi); // 返回生成的新对象 cloneObj = (T) oi.readObject(); oi.close(); } catch (Exception e) { e.printStackTrace(); } return cloneObj; }
// 构造InputStreamReader时,我们需要传入InputStream, // 还需要指定编码,就可以得到一个Reader对象 // 关闭对象时,只需要关闭最外层的Reader对象即可(它会在内部自动调用InputStream的close()方法) try (Reader reader = new InputStreamReader(new FileInputStream("src/readme.txt"), "UTF-8")) { // TODO: }
try (Writer writer = new FileWriter("readme.txt", StandardCharsets.UTF_8)) { writer.write(‘H‘); // 写入单个字符 writer.write("Hello".toCharArray()); // 写入char[] writer.write("Hello"); // 写入String }
如下例子代码: FileInputStream is = new FileInputStream("."); BufferedInputStream bis = new BufferedInputStream(is); bis.close(); 从设计模式上看: java.io.BufferedInputStream是java.io.InputStream的装饰类。 BufferedInputStream装饰一个 InputStream 使之具有缓冲功能, is要关闭只需要调用最终被装饰出的对象的 close()方法即可, 因为它最终会调用真正数据源对象的 close()方法。 BufferedInputStream的close方法中对InputStream进行了关闭, 下面是jdk中附带的源代码: java.io.BufferedInputStream的api: close public void close()throws IOException 关闭此输入流并释放与该流关联的所有系统资源。 如果不想用上述方式关闭流:可以逐层关闭,主要最外层的先关闭### 如下例子: public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("d:\\a.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); bw.write("java IO close test"); //从内带外顺序顺序会报异常 fos.close(); osw.close(); bw.close(); } 报出异常: Exception in thread "main" java.io.IOException: Stream closed at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:26) at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:99) at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190) at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111) at java.io.BufferedWriter.close(BufferedWriter.java:246) at com.my.test.QQ.main(QQ.java:22) 如下例子: public static void main(String[] args) throws Exception { FileOutputStream fos = new FileOutputStream("d:\\a.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); bw.write("java IO close test"); // 从外到内顺序关闭ok bw.close(); osw.close(); fos.close(); } 验证ok
原文:https://www.cnblogs.com/shineipangtuo/p/13763449.html