簡體   English   中英

如何在Java中附加文件

[英]how to append file in java

如何將highscore按降序附加到highscore.txt文件中的正確位置? 該方法使用之前創建的readHighScore(int score)方法來查找應在其中插入記錄的行號。 這是我到目前為止所得到的:

public static void recordHighScore(String name, int score){
            File file = new File("Test/highscore.txt");
            FileWriter fwriter = new FileWriter(file, true);
            try{
                String userName = name+","+score;
                fwriter.add(readHighScore(score), userName);

            }catch(IOException io){
                System.out.println("Missing File!");

            }

            /*Writes the high score into highscore.txt file, at the correct position (in descending order). This
            method uses readHighScore( ) method to find the line number where the record should be
            inserted.*/
        }

如果要在末尾附加數據非常容易,而如果要在中間附加數據幾乎是不可能的。 輕松讀取內存中的所有文件,進行更改並再次保存所有文件,覆蓋舊的信息非常容易。

例如:

// read file to arraylist
Scanner s = new Scanner(new File("filepath"));
List<Score> list = new ArrayList<Score>();
while (s.hasNext()){
    String[] a = s.next().split(","); 
    list.add(new Score(a[0], a[1]); ); // Score is class with name and score fields
}
s.close();

// working with List<Score>
// add new score to List<Score>
// save List<Score> to file like in your code

如何 append arraylist<object> 在 java 的文件中<div id="text_translate"><p>給定的 function 寫入文件但再次調用它會覆蓋文件中的先前列表 object 例如</p><p>如果數組列表索引 0 包含名稱 - “aman”,我稱之為 function 它將“aman”保存在文件中。 但是當索引 1 的名稱為“lavesh”時,它會覆蓋以前的數據</p><p>它在像“lavesh”這樣的文件中,但我想要它像“aman lavesh”</p><pre class="lang-java prettyprint-override"> public void alter_file( ArrayList&lt;Flight_registrie&gt; x) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(" Flight Registrie.txt")); oos.writeObject(x); x.clear(); oos.close(); } catch (IOException e) { System.out.println("An I/O error occurs"); e.printStackTrace(); } }</pre><p> 沒有錯誤,但我的方法可能是錯誤的</p></div></object>

[英]How to append arraylist<object > in a file in java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM