FileOperater


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
* 文件操作类
*
* @author keating
*/
public class FileOperater {

/**
* 文件复制方法
* @throws IOException
*/
public static void copyFile(File source, File out) throws IOException {
FileInputStream inFile = null;
FileOutputStream outFile = null;
try {
inFile = new FileInputStream(source);
outFile = new FileOutputStream(out);
byte[] buffer = new byte[1024];
int i = 0;
while ((i = inFile.read(buffer)) != -1) {
outFile.write(buffer, 0, i);
}
} catch (IOException e) {
throw e;
} finally {
try {
if (outFile != null)
outFile.close();
}catch(IOException ex) {
throw ex;
}finally {
if(inFile != null)
inFile.close();
}
}
}

/**
* 文件打开方法
* @throws IOException
*/
public static void openFile(File file) throws IOException {
Runtime r = Runtime.getRuntime();
String name = file.getAbsolutePath().replace(" ", "%20");
r.exec("cmd /c start " + "file:///" + name);
}

/**
* 得到一个文件的内容,以字符串的形式返回
* @throws IOException
*/
public static String readText(File file) throws IOException {
StringBuilder content = new StringBuilder();
BufferedReader reader = null;
try {
InputStreamReader pr = new InputStreamReader(new FileInputStream(file), "UTF-8");
reader = new BufferedReader(pr);
String temp = null;
while ((temp = reader.readLine()) != null) {
content.append(temp);
}
} catch (IOException e) {
throw e;
} finally {
if(reader != null) {
reader.close();
}
}
return content.toString();
}

/**
* 将字符串写到一个文件中去,实际上是删除这个文件重新创建,然后写内容
*
* @throws IOException
*/
public static void writeText(File file, String text) throws IOException {
OutputStreamWriter pw = null;
try {
pw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
pw.append(text);
} catch (IOException e) {
throw e;
} finally {
if (pw != null)
pw.close();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值