私は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();
}
各アカウントの情報は、それぞれの行に書かれていますか? – dorukayhan
各行は各アカウント用です。それはあなたが求めているものですか? –
サンプルデータ行にはフィールド間に区切り文字がありません。どのようにフルネームが終了するのかはどうやって分かりますか? –