2016-05-16 3 views
0

私はusername、fullName、password、id、およびpointsを持つclassアカウントを持っています。 すべてのアカウントはファイルに保存されています。私は自分のファイルに複数のアカウントを持っています。これは、テキストファイルの1つのアカウントの例です。Javaの既存のtxtファイルを編集する

Miljan9602 Rakita Miljan miljan123 1463433398614 0.0 

例えば、ユーザ名、フルネーム、パスワード、IDとポイント今

、私は私のユーザー名のためのポイントを変更したい場合。私が最初に行うことは、ファイル内のすべての行を調べて、同じユーザー名を見つけたらすべてのユーザー名を比較することです。私はポイントを変更するだろう。これは私の考え方です。ファイルでそれを編集する方法は知らないだけです。

public void edit(String username, double points) 
{ 
    File f = new File("Accounts.txt"); 

    // file doesnt exist, return from method 
    if(!f.exists()) 
     return; 
    Scanner sc = null; 

    try 
    { 
     sc = new Scanner(f); 

     while(sc.hasNextLine()) 
     { 
      String line = sc.nextLine(); // Take whole line 
      String split[] = line.split(" "); // Split it so i can check username 

      if(split[0].equals(username)) 
      { 
       String change = Double.toString(points); // Make string from double 
       split[5] = change; // on fifth index are points 

       /* My question is now how to edit file and to replace my new points 
       * with old points ? 
       * Miljan9602 Rakita Miljan miljan123 1463433398614 0.0 <- Need to change this 0.0 with split[4]; 
       */ 
      } 
     } 
    }catch(Exception e) 
    { 
     e.printStackTrace(); 
    }finally{ 
     // finally will always close file 
     sc.close(); 
    } 
+0

各アカウントの情報は、それぞれの行に書かれていますか? – dorukayhan

+0

各行は各アカウント用です。それはあなたが求めているものですか? –

+0

サンプルデータ行にはフィールド間に区切り文字がありません。どのようにフルネームが終了するのかはどうやって分かりますか? –

答えて

0

Apache's Commons IOライブラリを使用できます。あなたが必要とするものはすべてそこに見つけることができます。また、hereはCommons IOのGitHubミラーです。見る価値がある。

0
{ 
File f = new File("Accounts.txt"); 

FileWriter fw = new FileWriter(f); 
// file doesnt exist, return from method 
if(!f.exists()) 
    return; 
Scanner sc = null; 

try 
{ 
    sc = new Scanner(f); 

    while(sc.hasNextLine()) 
    { 
     String line = sc.nextLine(); // Take whole line 
     String split[] = line.split(" "); // Split it so i can check username 
     if(split[0].equals(username)) 
     { 
      String change = Double.toString(points); // Make string from double 
      split[5] = change; // on fifth index are points 

      /* My question is now how to edit file and to replace my new points 
      * with old points ? 
      * Miljan9602 Rakita Miljan miljan123 1463433398614 0.0 <- Need to change this 0.0 with split[4]; 
      */ 
      for(int i = 0; i < spit.length(); i++{ 
       fw.write(split[i] + " "); 
      } 
      System.getProperty("line.separator"); 
     } 
    } 
}catch(Exception e) 
{ 
    e.printStackTrace(); 
}finally{ 
    // finally will always close file 
    sc.close(); 
    fw.close(); 
} 

1はFiles.readAllLines()を使用し、バックファイルシステムへの全体の読み取りテキストを書くことがあるので、これは

+0

あなたはもっと細かいことができますか、私はあなたが私にしたいことを理解しているか分からない:) –

+0

うーん、それdoesnt仕事。このコードの後に​​私のファイルは空です。 –

0

を動作するはずです。


もっと

Path path = Paths.get(".../Accounts.txt"); Charset charset = StandardCharsets.UTF_8; List<String> lines = new ArrayList<>(); if (Files.exists()) { Files.readAllLines(path, charset); for (int i = 0; i < lines.size(); ++i) { String split[] = lines.get(i).split(" "); if (split[0].equals(username)) { String change = String.valueOf(points); split[5] = change; // on fifth index are points StringBuilder sb = new StringBuilder(); for (String value : split) { if (sb.length() != 0) { sb.append(' '); } sb.append(value); } lines.set(i, sb.toString()); // Changes the line. Files.write(path, lines, charset); break; // leave loop } } } 

は、テキストファイルの一行を変更するには

を説明し、原則として1は完全に安全で、それをテキスト全体をロードし、ラインを変更した後する必要があります。 その理由は、行の変更に応じてファイルが縮小または拡大する可能性があるためです。 いくつかのねじれがあっても、これは最適ではありません。 Files.readAllLinesはそのための素晴らしい方法です。一つは、また、書式を変更する場合があります:

  • 固定長レコード(行)のRandomAccessFileを可能にします。しかし、テキストが手動で編集される危険性があり、ファイルが壊れてしまい、フィールド長が制限されてしまいます。
  • .properties形式では、Propertiesクラスを使用してアクセスできます。要件は鍵であり、形式はkey = valueです。また、テキストにはエスケープ文字(\)があります。

Accounts.txtをコアにしておくことができます。たとえばAccountsというクラスでは、すべてをユーザー名からアカウントにマップとして表すことができます。

class Account { 
    public final String userName; // Unmodifiable key 
    public String password; 
    ... 
} 
class Accounts { 
    private Map<String, Account> accountsByUserName = new HashMap<>(); 
    public void loadAccounts() throws IOException { ... } 
    public void saveAccounts() throws IOException { ... } 
    public Optional<Account> getAccountByUserName(String userName) { ... } 
    public void deleteAccountByUserName(String userName) { ... } 
    public void createAccount(Account account) throws AlreadyExistsException { ... } 
} 
+0

現在のテキストファイルを編集するだけの他の方法はありませんか? –

+0

行を順番に読み込み、_second_ファイルに書き戻す(おそらく変更される)可能性があります。最後にファイルを置き換えてください。このすべては、多数のユーザーにスケーラビリティがなく、非常に脆い(何かがうまくいかない場合)。次に、h2、Derbyなどの組み込みデータベースが必要になります。 –

関連する問題