已知文件a.txt文件中的内容为“bcdeadferwplkou”,请编写程序读取该文件内容,并按照自然顺序排序后输出到b.txt文件中。即b.txt中的文件内容应为“abcd…………..”这样的顺序。
我这有点问题,排序结果:bcaddeefklopruw不对,有大神还望指点
- package com.wxy002;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.lang.reflect.Array;
- import java.nio.CharBuffer;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeMap;
- import java.util.TreeSet;
- public class Test22
- {
- public static void main(String[] args)
- {
- BufferedReader br = null;
- BufferedWriter bw =null;
-
- try {
- br =new BufferedReader(new FileReader("a.txt"));//因为源文件是文本文件所以用缓冲字符流读取
- bw = new BufferedWriter(new FileWriter("b.txt"));//因为目标文件也是文本文件所以用缓冲字符流写入
-
- String str ;
- while((str = br.readLine())!=null)
- {
-
- bw.write(sort(str));
-
- }
-
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally
- {
- try {
- br.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- bw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-
-
- }
- public static String sort(String str)//冒泡排序
- {
- char[] ch = str.toCharArray();
- StringBuilder sb = new StringBuilder();
-
- for (int i = 0 ; i<ch.length-1 ; i++)
- {
- for(int j =i ; j<ch.length -i -1;j++)
- {
- if(ch[j] > ch[j+1])
- {
- char c = ch[j];
- ch[j] =ch[j+1];
- ch[j+1] = c;
- }
- }
- }
-
- for(int i = 0 ; i<ch.length; i++)
- {
-
- sb.append(ch[i]);
-
-
- }
- str = sb.toString();
- System.out.println(str);
- return str;
- }
-
- }
复制代码 |
|