package com.swift; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class IO_sort_content { public static void main(String[] args) { /* * 已知文件 a.txt 文件中的內容為“bcdeadferwplkou”, * 請編寫程序讀取該文件內容,並按照自然順序排序后輸出到 b.txt 文件中。 * 即 b.txt 中的文件內容應為“abcd…………..”這樣的順序。 */ try { FileInputStream fis=new FileInputStream("E:\\neck\\a.txt"); FileOutputStream fos=new FileOutputStream("E:\\neck\\b.txt"); byte[] kilo=new byte[4*1024]; int len; while((len=fis.read(kilo))!=-1) { fos.write(kilo,0,len); fos.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
上面只是做到讀取並寫入另一個文件,並沒有進行排序
下面是排序的方法
package com.swift; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class IO_sort_content { public static void main(String[] args) { /* * 已知文件 a.txt 文件中的內容為“bcdeadferwplkou”, * 請編寫程序讀取該文件內容,並按照自然順序排序后輸出到 b.txt 文件中。 * 即 b.txt 中的文件內容應為“abcd…………..”這樣的順序。 */ try { BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("E:\\neck\\a.txt"),"GB2312")); StringBuffer sb=new StringBuffer(); String str; while((str=br.readLine())!=null) { sb.append(str); } String source=sb.toString(); char[] src=source.toCharArray(); Arrays.sort(src); String destination=String.valueOf(src); System.out.println(destination); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:\\neck\\b.txt"),"GB2312")); bw.write(destination); bw.flush(); sb.setLength(0); sb.append(destination); System.out.println(sb.reverse());//逆序 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
也可以把字節流直接排序了,比較精簡
package com.swift; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class IO_sort_content { public static void main(String[] args) { /* * 已知文件 a.txt 文件中的內容為“bcdeadferwplkou”, 請編寫程序讀取該文件內容,並按照自然順序排序后輸出到 b.txt 文件中。 即 * b.txt 中的文件內容應為“abcd…………..”這樣的順序。 */ try { FileInputStream fis = new FileInputStream("E:\\neck\\a.txt"); FileOutputStream fos = new FileOutputStream("E:\\neck\\b.txt"); int len; byte[] arr = new byte[fis.available()]; while ((len = fis.read(arr)) != -1) { System.out.println("排序...."); Arrays.sort(arr); System.out.println("寫入..."); fos.write(arr,0,len); fos.flush(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }