读写文件有很多种方式,这里只记录一种
读文件 // 一次性读完
public static String readFile() {
String str = "";
File file = new File("文件路径");
try {
FileInputStream in = new FileInputStream(file);
int size = in.available();//文件长度
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
str = new String(buffer, "utf-8");
str = str.replaceAll("\r\n","\n");//某些换行问题解决,根据需求而定
} catch (IOException e) {
return null;
}
return str;
}
写文件:
public static void outFile(String s) {
File file = new File("生成的文件路径");
try (FileOutputStream fop = new FileOutputStream(file)) {
// 文件不存在,创建文件
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = s.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
linux 和unix下换行符为:"\n"
windows下的换行符为:"\r\n"
如果需要把文件内容插入到数据库,可根据需求互换两种系统下的换行符。
删除文件代码如下:
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}