为什么不能在Java中向文件添加文本?

时间:2019-07-15 00:00:59

标签: java file

似乎它总是在尝试写入或读取时创建一个新文件。 每行以播放器的名称开头,如果存在,播放器应在末尾添加得分,如果没有,则创建新行并写入信息。 .......................

public class JogadorData {

private String nome_player;
private Scanner is;
private FileWriter os;
    // this file exists
private final String path = "src/Data/JogadorData";

public JogadorData(String nome_player) {
    this.nome_player = nome_player;
    try {
        is = new Scanner(new File(path));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } 
    try {
        os = new FileWriter(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void escreverScore(String score) {
    if (jogadorNovo(nome_player)) {
        try {
            os.write(nome_player + " " + score);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    else {
        escreverResultadoJogadorExistente(score);
    }

    try {
        is.close();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

    // returns true if it is a new player
    private boolean jogadorNovo(String nome_player) {

    while (is.hasNextLine()) {
        String linha = is.nextLine();
        String[] info = linha.split(" ");

        if (info[0].equals(nome_player)) {
            return false;
        }
    }

    return true;
}
}

.................................... .................................... 测试:

 public class TESTE {

public static void main(String[] args) {

    JogadorData jogador = new JogadorData("Manelina");

    jogador.escreverScore("100");

    // System.out.println(jogador.lerMelhorResultado());

}

}

1 个答案:

答案 0 :(得分:0)

下面的示例简化了对现有文件的读/写操作,格式与尝试执行的操作类似。该代码的作用是通过Files#readAllLines从正在加载的文件中读取每一行,然后遍历每一行,(将您的逻辑放在我对if语句进行注释的位置,然后将output.add追加到该行的新版本中正在修改,并将其存储在数组列表“ output”中,然后将文件保存到Files#write定义的路径

List<String> output = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("Path/To/File.txt"));
for (String line : lines) {
    //... if (playerExists(line))
    output.add(line + " " + score);
}
Files.write(Paths.get("Path/To/Save/File.txt"), output);
相关问题