文件操作入门
这段代码实现了最基础的文件操作:查,搜,读写和copy
我把这段代码传上来,以方便自己和他人的学习:
package fileprogram;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
publicclass fileIO {
//检测是否存在:
publicvoid testFile(){
File file = new File("D:\\text.txt");
if(file.isDirectory()&&!file.exists()){
//file.mkdir();这个只能创建一级目录
file.mkdir();
//可以创建多级目录
file.mkdirs();
try{
//当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
}
//如果存在:更改文件名
if(file.isFile()){
//打印该文件的绝对路径
System.out.println(file.getAbsolutePath());
file.renameTo(new File("D:\\rename.txt"));
}
}
publicvoid find(File file,String findString){
//列出所有的子目录
File[] sonFiles = file.listFiles();
if(sonFiles != null){
for(int i = 0;i<sonFiles.length;i++){
File f = sonFiles[i];
if(f.isFile()){
if(f.getName().indexOf(findString)!=-1){
System.out.println(f.getAbsolutePath());
}else{
find(f,findString);
}//else
} //if
}//for
}//if
}//
publicvoid readFile(){
try{
FileInputStream fis = new FileInputStream("D:\\test.txt");
System.out.println("fis.available()="+fis.available());
//新建一个与文件大小相同的字节数组
byte[] bytes = newbyte[fis.available()];
//一次性把所有的数据都读到这个数组中
fis.read(bytes);
String content = new String(bytes,"GB2312");
System.out.println(content);
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
//写入操作:
publicvoid writeFile(){
try{
FileOutputStream fos = new FileOutputStream("D:\\text2.txt");
String content = "Hello world";
byte[] bytes = content.getBytes("gb2312");
fos.write(bytes);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
//文件复制:
publicvoid copyFile(String src,String dest){
try {
FileInputStream fiStream = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
int c = fiStream.read();
while(c!=-1){
c= c+12;//简单的加密代码
fos.write(c);
c = fiStream.read();
}
fiStream.close();//关闭
fos.close();//关闭
}catch(Exception e){
e.printStackTrace();
}
}
publicstaticvoid main(String[] args) {
fileIO FileIO = new fileIO();
File file = new File("D:\\text.txt");
//FileIO.find(file, ".java");
//FileIO.testFile();
FileIO.copyFile("D:\\text.txt", "D:\\text2.txt");
}
}