2015-08-08 58 views
-5

嗨,我做了一个包含jtextfield和几个jbuttons的程序。我想按jbutton,以便将jtextfields保存到计算机中。任何帮助都是有用的。试图发送数据到文本文件

+2

你为什么不看一个关于将数据保存到文件的教程?他们很丰富 – SamTebbs33

+0

你到目前为止已经尝试过什么? – Seb

+0

那么你的问题是什么?你知道如何做文件I/O吗?你知道如何在单击按钮时执行代码吗?你知道如何从文本字段中获取文本吗?当你问一个问题时具体。我们无法猜测是什么导致了你的问题。从“Java教程”开始。有I/O教程和使用Swing应该回答你所有的问题。 – camickr

回答

0

我认为这将帮助你..

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           

    if (jTxt_text.getText().isEmpty()) { 
     JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again."); 
    } else { 
     //get the text from the jTextField and save it into a varibale. 
     String inputText = jTxt_text.getText(); 
     //Where to save the file. 
     String savePath = "C:/test/sample.txt"; 

     //Creating a file object, file is an abstract representation of file and directory pathnames. 
     File tempFile = new File(savePath); 

     //Check wther the file is available or not. 
     if (!tempFile.exists()) { 
      try { 
       //Creates the file if it's not exsising. 
       tempFile.createNewFile(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

     try { 
      //writing process.. 
      FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile()); 
      BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter); 
      tempBufferWriter.write(inputText); 
      tempBufferWriter.close(); 

      JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved."); 
      jTxt_text.setText(null); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

仍然有一个小问题,此代码tempBufferWriter.write(inputText)返回void所以..我不知道如何检查wther从代码本身成功地完成了过程..

+0

我会给它一个机会 –

+0

我有很多文本字段在同一时间写15 15确切地说,他们并不都必须是字段。那么使用这段代码应该能够写出所有这些代码? –

+0

这是一个基本的代码,你可以获得一个'jTextField'的值并将其写入一个文本文件中......可能有'jTextAreas','JComboBoxes','jRadioButtons',所以你必须做的只是获取所有这些组件的值,然后保存到变量中并构建一个单独的字符串。并将其作为写入方法的参数传递。 – ZeroKool