该程序是将txt文件中形如“/w”这样的字符串去掉,遇到空格换行,网址形式则不作任何处理,并且去掉标点符号。修改后存入新的txt文件中。 package com; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; public class OutputBySort { public String readFromFile(File file) throws IOException {//读取文件并且转化 FileInputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } InputStreamReader ipsr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(ipsr);//创建bufferReader对象 String str = null; String str1 = null; String str2 = null; String str3 = null; int pos,length; StringBuffer sb = new StringBuffer();//创建stringBuffer try { while ((str = br.readLine()) != null) {//读一行 sb.append(str);//将读到的一行str加入到string缓冲区 sb.append("/r/n");//读入换行符 } } catch (IOException e) { e.printStackTrace(); } str1 = sb.toString();//转化为String str1 = str1.replaceAll("//D"+"/w","");//去标点 str1 = str1.replaceAll("/[a-zA-Z]+", "");//将/w类似的子串去掉 pos = str1.indexOf("html");//html的位置 length = str1.length(); str2 = str1.substring(0, pos+5);//网址 str2 = str2.replaceAll("//s+",""); str3 = str1.substring(pos+4, length);//网址以后的内容 str3 = str3.replaceAll("//s+", "/r/n");//将空格转化为换行 str3 = str2 + str3; return str3; } public void writeIntoFile(File file,String str)throws IOException{//写入到文件,str为要写入的String try{ String str1 = str; RandomAccessFile dos = new RandomAccessFile(file, "rw");//打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件 dos.seek(dos.length()); dos.write(str1.getBytes()); }catch(IOException e){ e.printStackTrace(); } } public void creatFolder(String folderPath){//创建新目录 try { File myFilePath = new File(folderPath); if (!myFilePath.exists()) {//不存在则重新创建一个 myFilePath.mkdir(); } } catch (Exception e) { e.printStackTrace(); } } public void Transformation(String oldFolderPath,String newFolderPath)throws IOException{//转化方法 String oldPath = oldFolderPath;//原有文件夹路径 String newPath = newFolderPath;//新文件路径 String str,string;//str用于接收readFromFile返回字符,string用于写入文件的文件路径 File file = new File(oldPath);//原来文件夹的对象 File[] childs = file.listFiles();//获得文件夹下所有子文件 creatFolder(newPath);//创建新目录 for(int i = 0;i<childs.length;i++) { string = childs[i].getName();//原名 string = newPath +"/"+ string;//写入的文件路径(新路径+原名) str = readFromFile(childs[i]); File f = new File(string); writeIntoFile(f,str); } } public static void main(String[] args) throws IOException{ OutputBySort out = new OutputBySort(); out.Transformation("E:/a", "E:/c"); } }