对文件和文件夹的一些操作

Yang_Hai_Quan 2012-04-09 11:49:41
/**
* 读取文件内容并返回字符串[适合文本文件]
* */
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());
}

}
}
...全文
69 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
安特矮油 2012-04-10
  • 打赏
  • 举报
回复
LZ是在分享代码吗?真是个好人啊

51,408

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧