試試這個。
public static Map<String, String> loadFile(Reader reader)
throws IllegalArgumentException{
Map<String, String> mapList = new TreeMap<String, String>();
if(reader == null)
{
throw new IllegalArgumentException("Reader not valid");
}
String line;
innerReader = new BufferedReader(reader);
int countLine = 0;
try
{
while((line = innerReader.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line Empty");
mapList.put("line"+String.valueOf(countLine), line);
countLine++;
}
} catch (IOException e) {
}
return mapList;
}
在主要添加此嘗試您的代碼。
Map<String, String> mapList = new TreeMap<String, String>(Collections.reverseOrder());
try {
mapList = loadFile(new FileReader("YourFile.txt"));
} catch (IOException e) {
e.printStackTrace();
}
for (Map.Entry entry : mapList.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
安,這是輸出。
line0,劑1 RF 2 0
行1,Agent2 RB 4 5
LINE2,劑4 CE 2 2
line3中,Agent3 RF 3 11
對於打印out in file add this:
private static PrintWriter innerWriter;
public static void printMap(Map<String, String> myMap, Writer writer)
throws IOException {
if(writer == null)
{
throw new IOException("Cannot open file");
}
innerWriter = new PrintWriter(writer);
for (Map.Entry entry : myMap.entrySet()) {
innerWriter.write(entry.getKey() + ", " + entry.getValue() + "\n");
//OR THIS FOR ONLY VALUES
// innerWriter.write(entry.getValue() + "\n");
}
innerWriter.close();
}
,這對主要
try {
printMap(mapList, new FileWriter("FileOutput.txt"));
} catch (IOException e) {
e.printStackTrace();
}
你能告訴工作/代碼你做了到現在爲止? –
「我想將所有行保存在不同的變量中」 - 聽起來你應該真的使用「列表」,例如'ArrayList'。 –
@JonSkeet OHMYGOD !!!看看是誰吧! –