最近看小说发现有些TXT下载下来阅读器识别不了,例如这种
研究了一下发现阅读器是【第N章、title】来识别的,所以写了一个Demo
public static void Test(String oldfilePath, String newfilePath) {
File file = new File(oldfilePath);
//判断文件存在并且是文件
Boolean boo = file.exists() && file.isFile();
System.out.println(boo);
if (boo) {
BufferedReader bufferedReader = null;
try {
InputStream in = new FileInputStream(oldfilePath);
//构造一个BufferedReader类来读取文件
// bufferedReader = new BufferedReader(new FileReader(file,""));
bufferedReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
String linetxt = null;
//result用来存储文件内容
StringBuilder result = new StringBuilder();
//按使用readLine方法,一次读一行
while ((linetxt = bufferedReader.readLine()) != null) {
linetxt = linetxt.trim().replaceAll("[\\n\\r]", "");
System.out.println("linetxt = " + linetxt);
File newfile = new File(newfilePath);
PrintStream ps = new PrintStream(new FileOutputStream(newfile, true));
if (linetxt.contains("、")) {
String title = linetxt.substring(0, linetxt.indexOf("、"));
if (isNumber(title)) {
String newconttent = "第" + title + "章" + linetxt.substring(linetxt.indexOf("、"));
result.append(newconttent);
ps.println(newconttent);// 往aim.txt文件里写入字符串
continue;
}
}
ps.println(linetxt);// 往aim.txt文件里写入字符串
}
//输出读出的所有数据(StringBuilder类型)
System.out.println(result);
//对文件内容操作
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("找不到指定的文件");
}
}
public static void main(String[] args) {
String oldfilePath = "F:\\小说\\夜的命名术.txt";//content.txt路径。记得改
// String oldfilePath = "F:\\谷歌下载文件\\夜的命名术 (2).txt";//content.txt路径。记得改
String newfilePath = "F:\\小说\\test.txt";//aim.txt路径,记得改
Test(oldfilePath, newfilePath);
// String str = "こんなに静かに座っているのもよさそうですが、この少年の沈黙ぶりは本当にきれいですね。";
}
/**
* 是否数整数或者小数(是否为数字类型)
*
* @param str 需要判断的数据
* @return true:是数字,false:不是数字
*/
public static boolean isNumber(String str) {
String pattern = "^\\d+(\\.\\d+)?$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
return m.matches();
}
结果:
运行可能会有乱码问题,打开TXT另存为UTF-8,用最下面的支持日文