四种复制文件方法
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
public class CopyDemo1 { public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("a.txt")); BufferedWriter writer = new BufferedWriter(new FileWriter("b.txt"))) { copy5(reader, writer); } catch (IOException e) { e.printStackTrace(); } }
public static void copy1(InputStream in, OutputStream out) throws IOException { int data; while ((data = in.read()) != -1) { out.write(data); } }
public static void copy2(InputStream in, OutputStream out) throws IOException { byte[] bytes = new byte[1024]; int len; while ((len = in.read(bytes)) != -1) { out.write(bytes, 0, len); } }
public static void copy3(Reader reader, Writer writer) throws IOException { int data; while ((data = reader.read()) != -1) { writer.write(data); } }
public static void copy4(Reader reader, Writer writer) throws IOException { char[] chars = new char[1024]; int len; while ((len = reader.read(chars)) != -1) { writer.write(chars, 0, len); } }
public static void copy5(BufferedReader reader, BufferedWriter writer) throws IOException { String s; while ((s = reader.readLine()) != null) { writer.write(s); writer.newLine(); } } }
|
FileFilter
用于抽象路径名的过滤器。
boolean accept(File pathname)
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class Test3 { public static List<File> search(File src) { File[] files = src.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && file.getName().endsWith(".txt"); } }); return Arrays.asList(files); }
public static void main(String[] args) { File src = new File("D:\\temp"); List<File> list = search(src); for(File f : list) { System.out.println(f); } } }
|
IO流
IO流:
---------------- The End ----------------