博客:http://blog.csdn.net/muyang_ren
1.快速读取一个文本文件,将文件的内容输出到一个新文件;
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.列出某一目录下的后缀为”.java”的文件列表
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("打开目录失败!");
}
}
}
3.复制图片文件
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();
}
}
}
原文地址:http://blog.csdn.net/muyang_ren/article/details/46493057