一、创建文件的坑(java不能同时创建不存在的父目录和文件)
你是否遇到过明明文件路径完全正确,编译也没问题,运行却始终报bug?如下图
其实是你创建文件时,它的父目录不存在,因为java不支持父目录和文件同时创建,
就会一直报下面两个bug:
- java.io.IOException: 系统找不到指定的路径
- FileNotFoundException:(你设定的路径)
解决方法:将目录和文件分开创建就行
(小细节:java支持同时创建多级目录)
代码如下:
File ctFile(File fileNew) { //文件如果不存在就创建,注意java不能目录和文件同时创建
if (!isFileExist(fileNew)) {
boolean ctFileResult;
File fileParent = fileNew.getParentFile(); //获取文件的父目录
if (!fileParent.exists() && !fileParent.isFile()) { //如果文件的父目录不存在就创建父目录
fileParent.mkdirs(); //父目录可以多级同时创建
}
try {
ctFileResult = fileNew.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileNew;
}
boolean isFileExist(File file) { //判断文件是否存在,以及判断文件是目录还是文件
return file.exists() && file.isFile();
}
二、文本编码转换的坑(天有多高就有多糟心)
步骤:
- 获取特定编码流(读写差不多):BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsetName));
- 输入输出文本:bw.write(text);
- 关闭流:bw.close();
- 处理异常是个好习惯 :首先不用调用一次抛一次,其次一般定位bug直接到有问题代码(我遇到过出bug却乱定位的,解决了,万事无绝对)
代码如下:
class FileTextDalInk {
public void saveFile(String text, File file, String charsetNameWriter) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), charsetNameWriter));
bw.write(text);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String openFile(File file, String charsetNameReader) {
String strRead = "";
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(
new FileInputStream(file), charsetNameReader));
String temp = "";
while ((temp = bf.readLine()) != null) {
strRead += temp + "\r\n"; //据说 %n 是平台无关的换行符,没试验过
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return strRead;
}
}
该代码java通用
!上面代码最关键的一点是使用FileInputStream用指定编码读取文件,即 (new FileInputStream(file), charsetNameReader) (输出也一样)
解决文本编码转换乱码的思路(辛酸泪一把):
- 代码是否异常:字母拼错、流名写错、流输出的位置出错等
- 流读入前的文本编码是否弄错:即这里的charsetName–>FileInputStream(file), charsetName)
- 流的输出编码是否弄错
- 使用的语言是否支持读入写出的编码:如java本身不支持Hex编码(二进制)
三、String初始化值的坑
这个只是小细节
String str = null;
String str = "";
- 如果string初始化值为null,那么有些编码是会把他记录为“null”的,即 String str = null; ------> String str = “null”;
- 该问题目前只在读取输出文件时出过