【发布时间】:2015-03-25 09:56:36
【问题描述】:
我正在制作一个小 gui,在其中我将数据从文本文件读取到不同的 JComboBoxes,用户在 JComboBoxes 中进行编辑,然后将其保存在新的文本文件中。我的新文件被保存但不是读取时的格式。 代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
public class A extends JPanel
{
public A() {
JPanel buttonPanel = new JPanel();
add(buttonPanel);
buttonPanel.setLayout(new GridLayout(0, 2, 10, 10));
JComboBox combo1 = new JComboBox();
combo1.addItem("1ms");
combo1.addItem("2ms");
buttonPanel.add(combo1);
JComboBox combo2 = new JComboBox();
combo2.addItem("1ms");
combo2.addItem("2ms");
buttonPanel.add(combo2);
JComboBox combo3 = new JComboBox();
combo3.addItem("1ms");
combo3.addItem("2ms");
buttonPanel.add(combo3);
JComboBox combo4 = new JComboBox();
combo4.addItem("1ms");
combo4.addItem("2ms");
buttonPanel.add(combo4);
JComboBox[] fieldBoxs = new JComboBox[4];
fieldBoxs[0] = combo1;
fieldBoxs[1] = combo2;
fieldBoxs[2] = combo3;
fieldBoxs[3] = combo4;
ArrayList<String> list = new ArrayList<String>();
final StringBuilder temp = new StringBuilder();
try{
InputStream ips=new FileInputStream("test.txt");
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
boolean found = false;
while ((line=br.readLine())!=null) {
String[] s = line.split(" ");
list.add(s[0]);
list.add(s[1]);
if (s[0].equals("0") && !found)
{
found = true;
temp.append(line).append("\r\n");
}
else if (found)
{
temp.append(line).append("\r\n");
}
}
br.close();
}
catch (Exception e){
e.printStackTrace();
}
for(int i = 0; i < fieldBoxs.length; i++) {
fieldBoxs[i].setSelectedItem(list.get(i));
}
JButton button = new JButton("SAVE");
buttonPanel.add(button);
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < fieldBoxs.length; i++)
{
Object Value = fieldBoxs[i].getSelectedItem();
con.append(" ");
con.append(Value);
con.append("\r\n");
}
FileWriter filewriter = new FileWriter(new File("A.txt"));
filewriter.write(con.append(temp).toString());
filewriter.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args) {
A app = new A();
JFrame m = new JFrame("A");
m.getContentPane().add(app);
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m.pack();
m.setVisible(true);
}
}
这是我正在读取值的文件:测试
2ms 1ms
1ms 2ms
0 0
1 2
2 1
1 1
2 2
这就是我现在保存文件的方式:
2ms
1ms
1ms
2ms
0 0
1 2
2 1
1 1
2 2
我想保存为:
2 1
1 2
0 0
1 2
2 1
1 1
2 2
格式应与读取的格式相同,并且 ms 也不应出现在新保存的文本文件中。 任何帮助将不胜感激
【问题讨论】: