我正在尝试制作保存按钮,但我不知道该怎么做。我会解释一下我的程序。当有人启动程序时,它显示一个JOptionPane,用户需要写一个昵称,然后当他点击OK按钮时,它会将他的昵称保存在text.file中。这是我的代码的一部分。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.event.*;
public class SummerExamProject extends JFrame {
JButton Exit, About, Question1, Question2, Question3, Question4;
JPanel panel, panel2, panel3, panel4 ;
public SummerExamProject(){
initUI();
}
public void initUI(){
setTitle("Java");
setSize(500, 450);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame frame = new JFrame();
JFrame frame1 = new JFrame("");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(0,3,8,9));
String code = JOptionPane.showInputDialog(frame1, " Enter a nickname ", "Nickname needed", JOptionPane.WARNING_MESSAGE);
答案 0 :(得分:1)
如果要将昵称存储到文件,可以使用PrintWriter。假设您将昵称保存在名为nickname:
的String
变量中
String nickname = "myAwesomeNickname";
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("c:/nicknames.txt", true)));
out.println(nickname);
out.close();
} catch (IOException e) {
//exception handling
}
答案 1 :(得分:0)
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("text.txt"));
out.print(code); // your String here
} catch (IOException e) {
} finally {
if (out != null)
out.close();
}
text.txt
也可以是new FileOutputStream("D:/folder/text.txt")
之类的完整路径
不过,还有一些选项可以写入文件。