/**
* java读取文件中的指定内容
*
* @author 百度名称:文库帮助中心 QQ: 126 93 266 群: 160 973 354 菜鸟讨论
* @param args
* @throws Exception
* @since 0.1_Jun 7, 2013
*/
public static void main(String[] args) {
try {
File file = new File("E:\\b.txt"); // 需要写入的文件
OutputStream outPut = new FileOutputStream(file, true); // 用FileOutputSteam包装文件,并设置文件可追加
Scanner sc = new Scanner(new FileReader("E:\\a.txt")); // 需要读取的文件
String line = null;
while ((sc.hasNextLine() && (line = sc.nextLine()) != null)) { // 判断是否为空,或者最后一行
if (line != null && !"".equals(line)) { // 判读读取行是否为空
String[] lineList = line.split(" "); // 利用空格分开成String数组
if (lineList != null && lineList.length > 0) { // 判断苏数组大小
for (int i = 0; i < lineList.length; i++) { // 循环数组中的内容
if (lineList[i] != null && !"".equals(lineList[i])) { // 判断每一个内容是否为空
String reg = "^[A-Za-z]+$"; // 定义正则验证规则(是否由一串数字组成)
String str = lineList[i].trim();
boolean isCract = str.matches(reg); // 验证字符串
if (isCract) {
outPut.write(str.getBytes()); // 向文件中写入数据
outPut.write('\r'); // \r\n表示换行
outPut.write('\n');
}
}
}
}
}
}
outPut.close();// 关闭输出流
System.out.println("写入成功");
} catch (Exception e) {
e.printStackTrace();
}
}
Java读取Txt并写入新的Txt
最新推荐文章于 2021-02-20 04:27:27 发布