Java文件操作操作的代码网上多如牛毛,看人家的代码始终不如看自己的代码,所以本人亲自自己写了一个,为了以后可以简单的参考一下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* @文件的操作
* @author 陈罗志
*
*/
public class FileTest {
public FileTest(){
}
//字节流,按字节读取和写入,效率非常低,可以使用BufferedInputStream 封装
private FileInputStream fileInputStream;
private FileOutputStream fileOutputStream;
private File file ;
//对文件内容的操作(字符流),可以使用 BufferedReader进行封装
private FileReader fileReader;
private FileWriter fileWriter;
/**
* @文件的拷贝(字节流)然后删除
*/
public void copyFile(){
String path_in="c:\\t.exe";
String path_out="c:\\000t.exe";
try {
fileInputStream = new FileInputStream(path_in);
fileOutputStream = new FileOutputStream(path_out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//建立缓冲区,一次读取8k数据
byte[] b = new byte[8192];
try {
int byteReaded =fileInputStream.read(b);
int i =0;
while(byteReaded!=-1){
//把缓冲区数据写入文件
fileOutputStream.write(b,0,byteReaded);
System.out.println("第"+(i++)+"次写入,写入数据长度为:"+byteReaded);
byteReaded = fileInputStream.read(b);
}
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// file = new File(path_out);
// if(file.exists()){
// file.delete();
// }
}
/**
* @对文件夹内容的操作
*/
public void operateFile(){
String str ="";
try {
//遍历次文件
fileReader = new FileReader("c:\\test.txt");
int ch = fileReader.read();
while(ch!=-1){
str=str+String.valueOf((char)ch);
ch=fileReader.read();
}
System.out.println(str);
//在文件最末端加上一些内容
fileWriter = new FileWriter("c:\\test.txt",true);
fileWriter.write("\n我是大笨蛋!");
//要刷新缓冲区才会写入新文件
fileWriter.flush();
fileReader.close();
fileWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
FileTest fileTest = new FileTest();
fileTest.copyFile();
//fileTest.operateFile();
}
}