Today is relatively leisurely, so I will summarize the methods of file operation I have encountered recently, for the future use of fellow Daoists and poor Daoists:
//读取文件
public static String readFile(File f){
StringBuffer content= new StringBuffer();
byte[] b = new byte[1024*1024];
try {
InputStream reader = new FileInputStream(f);
while(reader .read(b) != -1){
content.append(new String(b,"UTF-8"));
}
reader .close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(reader != null){
try {
reader .close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content.toString().trim();
}
//解决读取文件时出现乱码问题
public static String readFileByUTF8(File file) {
StringBuffer content = new StringBuffer();
try {
if (file.isFile() && file.exists()) {
InputStreamReader isreader= new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader breader = new BufferedReader(isreader);
String fileLine;
while ((fileLine= breader.readLine()) != null) {
content .append(fileLine+ "\n");
}
isreader.close();
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
return content .toString();
}
//写入文件(得到的String内容写入文件中)
public static void writeFile(String content, String filepath) {
try {
File file = new File(filepath).getParentFile();
if (!file .exists()) {
file .mkdirs();
}
FileOutputStream fos = new FileOutputStream(filepath);
Writer out = new OutputStreamWriter(fos, "UTF-8");
out.flush();
out.write(content);
out.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
System.out.println("备份报文:" + filepath);
}
//写入文件(得到的byte[]内容写入文件中)
public static void writeFile(byte[] content, String filepath) {
try {
File file = new File(filepath).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fos = new FileOutputStream(filepath);
fos.write(content, 0, content.length);
fos.flush();
fos.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
System.out.println("Write File:" + filepath);
}
//文件拷贝 把一个文件内容拷贝到另一个中
public static void copyfile(String readpath, String writepath)
throws FileNotFoundException, IOException {
File file = new File(writepath).getParentFile();;
/*如果该文件为空,则创建文件夹*/
if (!file.exists()) {
file.mkdirs();
}
FileInputStream fis = new FileInputStream(readpath);
FileOutputStream fos = new FileOutputStream(writepath);
int len = 0;
byte[] b = new byte[1024];
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
fis.close();
fos.close();
}
//文件删除
public static void delFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
delFile(files[i]);
}
file.delete();
}
} else {
log.error("Delete File:" + file);
}
}