-5

所以,我又带着另一个问题回来了。^_^

这一次,我正在使用一个文件管理系统,当用户在登录屏幕窗口中输入用户名和密码时,我会在其中添加用户名和密码(此处未显示。我想写入一个将数据存储在两个单独的文本文件中线,但我不知道如何工作。

    File termsOfAgreement = new File(gamePath + "/terms.txt");

    try {
        termsOfAgreement.createNewFile();
    } catch (IOException exc) {
        JOptionPane.showMessageDialog(null, "Cannot create files! :(","Alas, something went wrong!", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }

    String pathway = termsOfAgreement.getPath();

    try {
        this.writeToFile(pathway, "username", "passcode");
    } catch (IOException exc) {
        JOptionPane.showMessageDialog(null, "Cannot work with files! :(","Alas, something went wrong!", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
}

public void writeToFile(String filePath, String username, String passcode) throws IOException {
    FileWriter filewriter = new FileWriter(filePath);
    BufferedWriter bufferedwriter = new BufferedWriter(filewriter);

    String[] credentials = {username, passcode};
    String writtenStuffs = "";

    for (String credit : credentials) {
        writtenStuffs += credit + "\n";
    }

    bufferedwriter.write(writtenStuffs);
    bufferedwriter.close();
 }
}

我做了一个数组,但似乎没有帮助。我正在向 Stack Overflow 寻求帮助。

提前致谢, :)

4

2 回答 2

0

尝试在行尾添加 \r\n 吗?

BufferedWriter writer = new BufferedWriter(new FileWriter(
            new File("whateverthefilenameis.txt")));
writer.write(username + "\r\n");
//if \r is deleted you won't see line changed in windows notepad
writer.write(password + "\r\n");
writer.close();

您可以使用 BufferedReader(FileReader(File "filename") readLine() 方法来读取文件“filename”中的每一行

它在我的 Windows 系统中正常工作。

于 2013-09-20T22:04:24.427 回答
0

这应该可以解决您的问题:

public void writeToFile(String filePath, String username, String passcode) throws IOException {
   PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
   writer.println(username + "\n" + passcode);
   writer.close();
}
于 2013-09-20T21:28:52.013 回答