对文件和文件夹的一些操作
/**
* 读取文件内容并返回字符串[适合文本文件]
* */
public String getContent(String filename){
Reader r = null;//文件读取器『输入流』
char[] buffer = new char[1024];//内存缓冲区,存放每次读取的数据
StringBuilder ret = new StringBuilder();
int len = 0;//表示每次读取的长度
try {
r = new FileReader(filename);
while(len!=-1){
len = r.read(buffer);
if (len!=-1){
ret.append(buffer,0,len);
}
}
return ret.toString();
} catch (Exception e) {
throw new RuntimeException("文件读取失败:["+e.getMessage()+"]");
} finally {
if (r!=null)
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 将字串content写入文件filename[适合文本文件]
* */
public void WriteConent(String filename,String content){
Writer w = null;
try {
w = new FileWriter(filename);
w.write(content);
w.flush();
} catch (Exception e) {
throw new RuntimeException("写入文件失败");
} finally {
try {
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 用户任何文件拷贝
* @throws IOException
* */
public void copyFile(String filename1,String filename2) throws IOException{
InputStream r = null;
OutputStream w = null;
byte[] buffer = new byte[1024*1024];
int len = 0;//存放每次读取的字节数
try {
r = new FileInputStream(filename1);
w = new FileOutputStream(filename2);
while(true){
len = r.read(buffer,0,1024*1024);
if (len==-1){
break;
}
w.write(buffer, 0, len);
w.flush();
}
} catch (Exception e) {
throw new IOException("拷贝文件失败:["+e.getMessage()+"]");
} finally {
try {
r.close();
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 判断文件或者目录是否存在
* */
public boolean IsExists(String filename){
return new File(filename).exists();
}
/**文件移动
* @throws IOException */
public void moveFile(String filename1,String filename2) throws IOException{
if(!IsExists(filename1))
return;
copyFile(filename1, filename2);
new File(filename1).delete();
}
/**
* 目录拷贝[该方法有bug]
* 例如:copyDir("d:\\test1","e:\\test1")
* @throws IOException
* */
public void copyDir(String srcDir,String targetDir) throws IOException{
File file1 = new File(srcDir);
File file2 = new File(targetDir);
if (!file2.exists())//如果目标目录不存在则主动创建
file2.mkdir();
for (File f : file1.listFiles()) {
System.out.println(f.getPath());
if (f.isDirectory()){//如果当前这个File是目录则开始递归调用当前方法
copyDir(f.getPath(),targetDir+"\\"+f.getName());
} else{//如果是文件则直接拷贝
copyFile(f.getPath(), targetDir+"\\"+f.getName());
}
}
}