文件排序后进行文本复制
现将TEXT1.TXT中的文本内容 复制到TEXT2.TXT中 并对其内容进行排序TEXT1.TXT中的文本内容为:b,5,q,10,f,6,9,d,3,c,1,e,4,2,7,8,a
最后输出结果为:a,b,c,d,e,f
1,2,3,4,5,6,7,8,9,10
难点在10要排在9的后面,试着做做就知道我说什么了,呵呵
import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; /** * 1.txt放在当前类的包中 * */public class SortText { public static void main(String[] args) throws Exception { InputStream in = SortText.class.getResourceAsStream("1.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String content = br.readLine(); String[] arrary = content.split(","); ArrayList<Integer> numList = new ArrayList<Integer>(); ArrayList<String> strList = new ArrayList<String>(); for (String str : arrary) { try { int numer = Integer.parseInt(str); numList.add(numer); } catch (NumberFormatException nfe) { strList.add(str); } } Integer[] numArray = numList.toArray(new Integer); String[] strArray = strList.toArray(new String); Arrays.sort(numArray); Arrays.sort(strArray); StringBuilder sb = new StringBuilder(); for (int i = 0; i < strArray.length; i++) { if (i > 0) { sb.append(","); } sb.append(strArray); } for (int i = 0; i < numArray.length; i++) { if (sb.length() == 0) sb.append(numArray); else sb.append(",").append(numArray); } String result = sb.toString(); String path = SortText.class.getResource("").getPath();//得到当前路径,2.txt与1.txt放在同一个目录中 //System.out.println(path); File newFile = new File(path + "2.txt"); PrintWriter pw = new PrintWriter(new FileOutputStream(newFile)); pw.print(result); pw.flush(); pw.close(); } }
页:
[1]