Java learning [file IO], java learning io
Blog: http://blog.csdn.net/muyang_ren
1. Read a text file quickly and output the file content to a new file;
package lhy.java_day3.oop;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class Test_BuffeRead { private static BufferedReader bfReader; private static BufferedWriter bfWriter; private static String str; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { bfReader = new BufferedReader(new FileReader("f:/java_day3.txt")); bfWriter = new BufferedWriter(new FileWriter("f:/write.txt")); while ((str=bfReader.readLine() )!= null) { System.out.println(str); bfWriter.write(str+"\r\n"); bfWriter.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
2. List the files suffixed with ". java" in a directory.
Package lhy. java_day3.oop; import java. io. file; public class Test_File {private static File fs;/*** @ param args */public static void main (String [] args) {String pathname = "e: \ test "; try {fs = new File (pathname); String [] str = fs. list (); for (String string: str) {if (string. endsWith (". java ") System. out. println (string) ;}} catch (NullPointerException e) {// TODO: handle exception System. out. Println ("failed to open the directory! ");}}}
3. Copy image files
package lhy.java_day3.oop;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class Test_picture { private static FileInputStream fis; private static FileOutputStream fos; private static int ret; private static byte[] b = new byte[2048]; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { fis = new FileInputStream("f:\\tu1.jpg"); fos = new FileOutputStream("f:\\tu2.jpg"); while (true) { ret = fis.read(b, 0, b.length); if(ret!=-1){ fos.write(b, 0, ret); }else { break; } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}