大体思想是新建一个word类重写compareTo方法
再使用Arrays工具类的sort方法进行排序。
Main类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Word[] words = new Word[44];
try {
fillWords(words);
} catch (IOException e) {
e.printStackTrace();
}
Arrays.sort(words);
System.out.println(Arrays.toString(words));
}
public static void fillWords(Word[] words) throws IOException {
System.out.println("输入文件地址");
int choose = 0;
String path = "";
Scanner input = new Scanner(System.in);
path = input.next();
StringBuilder text = new StringBuilder();
try {
FileInputStream inputStream = new FileInputStream(path);
byte[] bytes = new byte[1024];
int length = 0;
while ((length = inputStream.read(bytes)) != -1) {
text.append(new String(bytes, 0, length));
}
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println(e);
e.printStackTrace();
}
String s = text.toString();
String[] wordArray = ToArray(s);
for (int i = 0; i < words.length; i++) {
words[i] = new Word(wordArray[i]);
}
}
public static String[] ToArray(String s) {
int head = 0;
int count = 0;
String keyWord = "";
char[] letter = s.toCharArray();
String[] keyWords = new String[100];
for (int i = 0; i < letter.length - 1; i++) {
if (letter[i] == ' ') {
for (int j = head; j <= i; j++) {
keyWord = keyWord + letter[j];
}
keyWords[count++] = keyWord;
keyWord = "";
head = i + 1;
}
}
return keyWords;
}
}
Word类`
public class Word implements Comparable {
private final String word;
private final char firstChar;
public Word(String word) {
this.word = word;
this.firstChar = word.charAt(0);
}
@Override
public int compareTo(Object o) {
Word word1 = (Word) o;
return this.firstChar < ((Word) o).firstChar ? -1 : 1;
}
@Override
public String toString() {
return word;
}
}