Skip to content

Instantly share code, notes, and snippets.

@keating
Created June 1, 2012 08:27
Show Gist options
  • Save keating/2850318 to your computer and use it in GitHub Desktop.
Save keating/2850318 to your computer and use it in GitHub Desktop.
some helpers for file operation
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;
/**
* some helpers for file operation
*
* @author keating_andy_given
*/
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment