Java中的IO流
IO流:按传输单位分为,字节流和字符流,分别对应 InputStream/OutputStream 抽象类 和 Reader/Writer 抽象类。
按方向分为,输入流和输出流(从程序的角度来看)。输入流 == 读 ; 输出流 == 写
1. 文件流(FileInputStream / FileOutputStream)
如何正确关闭文件流:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//如何正确关闭文件流 public class RightCloseResource { public static void main(String[] args) { //test1();// 比较繁琐 test2();// 比较简单(jdk1.7以后) } private static void test2() { // java 7 提供的 资源自动关闭 File srcFile = new File("file/123.txt"); File destFile = new File("file/123_copy3.txt"); try ( // 打开资源的代码 InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); ) { // 可能出现异常的代码 byte[] buf = new byte[5];// 一般 1024 int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } } private static void test1() { InputStream in = null; OutputStream out = null; try { File srcFile = new File("file/123.txt"); File destFile = new File("file/123_copy2.txt"); in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); // 读并写 byte[] buf = new byte[5];// 一般 1024 int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 try { if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
copy文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//将 指定目录中的所有 .java 文件 复制到 指定的目录下,并修改后缀名为 .txt public class FileCopyDemo2 { public static void main(String[] args) { File srcDir = new File("./file/Folder1"); File destDir = new File("./file/Folder2"); //1. 找到源目录中所有 .java 文件 File[] fs = srcDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.endsWith(".java") && new File(dir,name).isFile()) return true; return false; } }); // 2. 对每一个文件 进行拷贝 InputStream in = null; OutputStream out = null; for (File file : fs) { try { in = new FileInputStream(file); String newName = file.getName().replace(".java", ".txt"); out = new FileOutputStream(new File(destDir, newName)); // 读并写 byte[] buf = new byte[5];// 一般 1024 int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } try { if(out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } // // 3. 拷贝后修改文件名称 (也可以在 new FileOutputStream()时候修改文件名字) // File[] files = destDir.listFiles(); // for (File file : files) { // String newName = file.getName().replace(".java", ".txt"); // file.renameTo(new File(destDir, newName)); // } } }
****************
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。