我有一個文件是排列的單詞列表,格式如下。它被格式化的方式,當我像記事本程序打開它,這似乎是根本不會被隔開,因此,例如,人的眼睛,第一位是這樣的:打破排列的單詞列表
ATHROCYTESDISHLIKEIRRECOVERABLENESSESEMBRITTLEMENTSYOUNGSOVER
但是當我複製和過去吧,它的出現格式如下:
ATHROCYTES
DISHLIKE
IRRECOVERABLENESSES
EMBRITTLEMENTS
YOUNGS
OVER
我想這個文件加載到一個數組,所以我可以排序。我正在努力如何正確地打破這一點。我發現使用此代碼:
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
打印出格式正確的文檔,就好像我要複製並粘貼它一樣。我使用此代碼,試圖在數組中加載:
String[] store = sb.toString().split(",");
由於沒有逗號,言不正確分離。認識到這一點,我也試過這個代碼,試圖在每一個新行把它分解:
String[] store = sb.toString().split(scan.nextLine());
這兩個給我同樣的結果,被印在同一行的話。現在有人可以將我的結果格式化爲數組嗎?
我包括我的代碼的其餘部分,因爲它有可能是在其他地方的問題源於:
public class InsertionSort {
public static String[] InsertSort(String[] args) {
int i, j;
String key;
for (j = 1; j < args.length; j++) { //the condition has changed
key = args[j];
i = j - 1;
while (i >= 0) {
if (key.compareTo(args[i]) > 0) {//here too
break;
}
args[i + 1] = args[i];
i--;
}
args[i + 1] = key;
return args;
}
return args;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Insertion Sort Test\n");
int n;
String name, line;
System.out.println("Enter name of file to sort: ");
name = scan.next();
BufferedReader reader = new BufferedReader(new FileReader(new File(name)));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
File file = new File(name);
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while((line = reader.readLine())!= null){
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String[] store = sb.toString().split("/n");
System.out.println(Arrays.toString(store));
/* Call method sort */
InsertSort(store);
n = store.length;
FileWriter fw = new FileWriter("sorted.txt");
for (int i = 0; i < store.length; i++) {
fw.write(store[i] + "\n");
}
fw.close();
}
}
你試過記事本++?它比記事本更好。這些行可能以換行符分隔(\ n)。這應該是你的分隔符。我對Java並不熟悉,但這看起來確實是你的問題。 –
我只是使用記事本,因爲它是一個.txt文件。我正在使用NetBeans中的所有代碼。這就是說,我試着編輯我的代碼來做split \ n,給我:String [] store = sb.toString()。split(「/ n」);但我仍然得到相同的結果,他們都在同一行。 – user3068177
那麼你使用了錯誤的斜線。此外,記事本+ +更好地讀取文件,這就是爲什麼我建議它。 –