![](/img/trans.png)
[英]How to Add Multiple Lines to Text File in Java (at different times?)?
[英]How do you write to a text document multiple times on different lines in Java?
所以,最近,我的父亲让我做了一个涉及收集用户名,密码等的项目,这样他就可以设置一个位置来查找他的所有登录信息。
我有一个程序,可以在每次运行程序时成功收集信息并编写新的文本文件。 我的目标是使信息存储在SAME文件中,但每组信息之间有一个空格。
这是我的代码(我道歉,我只有14岁):
package com.src.java;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class Info {
public static void main(String args[]) throws MalformedURLException,
IOException, InterruptedException {
boolean run = true;
while (run) {
JTextField companyName = new JTextField();
JTextField userName = new JTextField();
JTextField password = new JTextField();
JTextField accountNumber = new JTextField();
JTextField phoneNumber = new JTextField();
JTextField address = new JTextField();
UIManager.put("OptionPane.cancelButtonText", "Exit");
UIManager.put("OptionPane.okButtonText", "Create File");
Object[] message = { "Company name: ", companyName, "Username:",
userName, "Password:", password, "Account number:",
accountNumber, "Phone number:", phoneNumber, "Address:",
address, };
int option = JOptionPane.showConfirmDialog(null, message,
"Fill out your info...", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String cN = companyName.getText();
String uN = userName.getText();
String pw = password.getText();
String aN = accountNumber.getText();
String pN = phoneNumber.getText();
String ad = address.getText();
PrintWriter writer = new PrintWriter(cN + ".txt", "UTF-8");
writer.println("Company name: " + cN);
writer.println("User name: " + uN);
writer.println("Password: " + pw);
writer.println("Account number: " + aN);
writer.println("Phone number: " + pN);
writer.println("Address " + ad);
writer.close();
System.out.println("Wrote file: " + cN + ".txt");
Thread.sleep(500);
} else {
System.exit(0);
}
}
}
}
您写入的文件名随着输入的公司名称而变化。 硬编码文件名。
另外,将追加模式设置为true ...
如果要写入同一文件,可以在追加模式下打开,这样
new PrintWriter(new FileOutputStream(new File(filename),true));
true
将以追加模式打开文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.