【问题标题】:Writing to java file with GUI won't write correctly使用 GUI 写入 java 文件将无法正确写入
【发布时间】:2015-07-02 22:12:32
【问题描述】:

所以我要做的是将clientName, date, hour 写入fileWriter.txt 文档。我正在写信给Random Access Memory File。目前,如果我输入正确的值,它将以错误的格式输出!

例如:

Client Name = "James", Date="1", Hour="1" 出于某种原因,这将输出以下行 - 00,00, , null01,James ,1 , 他们正在根据他们输入的date 写入文件。

另外,有没有一种方法可以写入文件,然后删除 GUI 值以便它们可以输入新值?

这是我的代码:

##Correct Imports Here
public class CreateRandomDataFile extends JFrame implements ActionListener {

    private static JButton submit;
    private static JLabel output;
    private static JLabel bankDetails;
    private static JTextField txtClient = new JTextField("", 20);
    private static JTextField txtDate = new JTextField("",6);
    private static JTextField txtHour = new JTextField("",6);

    private static JLabel lblClient = new JLabel("Client");
    private static JLabel lblDate = new JLabel("Date");
    private static JLabel lblHour = new JLabel("Hour");


    private static Path file = Paths.get("fileWriter.txt");
    private static String s = "00,          ,  "
            + System.getProperty("line.seperator");
    private static FileChannel fc = null;
    private static int RECSIZE = s.length();


    private String client = "";
    private int date;
    private int hour;

    public CreateRandomDataFile(){
        super("Create Data File");
        setSize(500,500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



        output = new JLabel();
        submit = new JButton("Submit");

        bankDetails = new JLabel();
        setLayout(new FlowLayout());

        add(lblClient);
        add(txtClient);
        txtClient.addActionListener(this);

        add(lblDate);
        add(txtDate);
        txtDate.addActionListener(this);

        add(lblHour);
        add(txtHour);
        txtHour.addActionListener(this);


        add(submit);
        submit.addActionListener(this);

        add(output);


    }
    public void actionPerformed(ActionEvent e){
        Object source = e.getSource();
        int counter = 0;
        if(source == submit){
            client = txtClient.getText();
            //int newDate = Integer.parseInt(txtDate.getText());
            date = Integer.parseInt(txtDate.getText());
            hour = Integer.parseInt(txtHour.getText());


            try{
                 fc = (FileChannel)Files.newByteChannel(file, READ, WRITE);
//                OutputStream outStream = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
//                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream)); 

                String as=date + "";
                for(int i=as.length();i<2;i++){
                    //s="";
                    //s+="0";
                    s+="0" + date;
                }
                s+=","+client;
                for(int i=client.length();i<10;i++){
                    s+=" ";
                }
                s+= "," + hour;
                String hourLen = hour + "";
                for(int i=hourLen.length();i<2;i++){
                    s += " ";
                }

                byte[] data = s.getBytes();
                ByteBuffer buffer = ByteBuffer.wrap(data);
                fc.position(date * RECSIZE);
                fc.write(buffer);


//                writer.write(s, 0, s.length());
//                writer.newLine();
                fc.close();
            }
            catch(Exception eStream){
                System.out.println("Incorrect");
            }
        }
    }
     public static void main(String[] args){
        CreateRandomDataFile writer = new CreateRandomDataFile();
        writer.setVisible(true);
    }
}

这是我创建空文件的文件

public class createRandomNullFile {
     public static void main(String[] args){
        //Limit of student records allowed
        final int NO_STUDENTS = 100;

        //Create the file
        Path file = Paths.get("fileWriter.txt");

        //Default value for every record in the Random Access file (Students.txt)
        String s = "00,          ,  " 
                + System.getProperty("line.separator"); // After each record goto new line


        //Array - Get contents of string and add to data array
        byte[] data = s.getBytes();

        try{
         OutputStream output = new BufferedOutputStream(
                 Files.newOutputStream(file, CREATE));
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
        for(int i=0;i< NO_STUDENTS;i++){
            bw.write(s, 0, s.length());

        }
        bw.close();
        JOptionPane.showMessageDialog(null, "Empty file created");

        }
        catch(IOException ex){
            System.out.println("Error connecting or writing to file");
        }   
    }

【问题讨论】:

  • System.lineSeparator()代替System.getProperty("line.seperator")
  • @user1803551 - 这似乎没有解决它。它会改为添加一个空值。
  • 我没有将此作为答案发布,这是一个改进的评论。
  • 另外,您问的是两个看似无关的独立问题。你应该问他们不同的问题。虽然不清楚,但您的第二个代码似乎与您的第一个问题有关,而第一个代码与第二个问题有关。

标签: java swing user-interface filewriter


【解决方案1】:

我不清楚您希望如何获得除"00, , " 之外的输出,因为这是您编写的唯一字符串。这是您的代码稍作修改:

public class createRandomNullFile {

    public static void main(String[] args) {

        final int NO_STUDENTS = 10;
        Path file = Paths.get("fileWriter.txt");
        String s = "00,          ,  " + System.lineSeparator();

        try {
            OutputStream output = new BufferedOutputStream(Files.newOutputStream(file));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
            for (int i = 0; i < NO_STUDENTS; i++) {
                bw.write(s, 0, s.length());
            }
            bw.close();
        } catch (IOException ex) {
            System.out.println("Error connecting or writing to file");
        }
    }
}

创建一个包含内容的文本文件:

00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  
00,          ,  

【讨论】:

    【解决方案2】:

    您正在写入文件的字符串在类的顶部初始化

    private static String s = "00,          ,  "
            + System.getProperty("line.seperator");
    

    这是字符串的 "00,00, , null" 部分的来源(null 是由于属性名称不正确;它应该是 line.separator),您应该在使用之前清除此字符串或创建一个新的。

    要清除 GUI,请在写入文件后通过将以下内容放入 actionPerformed 方法来清除文本字段

    txtClient.setText("");
    txtDate.setText("");
    txtHour.setText("");
    

    【讨论】:

    • 它实际上并没有替换该行 - 它将值放在已经创建的行之后(“00,”,然后在此之后添加用户输入数据)。我该如何解决这个问题??
    • 你已经把“line.seperator”当它应该是“line.separator”,改变它应该足够了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多