如何从Java中的用户输入中读取并将其写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18070629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:10:51  来源:igfitidea点击:

How to read from user's input in Java and write it to a file

javafile-ioinput

提问by mario go

I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with the help of this file I will run a command.

我想创建一个简单的独立应用程序,它将从用户那里获取一些输入(一些数字和数学函数 f(x,y...))并将它们写入文件。然后在这个文件的帮助下,我将运行一个命令。

Basic ingredients that I need:

我需要的基本成分:

-- JTextArea for users input.

-- JTextArea 用于用户输入。

-- ButtonHandler/ActionListener and writing of the input to a (txt) file

-- ButtonHandler/ActionListener 并将输入写入 (txt) 文件

-- ButtonHandler/ActionLister to execute a command

-- ButtonHandler/ActionLister 执行命令

What is the best way to do it?

最好的方法是什么?

A current running code that I have (basically a toy) - which does not write anything, just executes - is:

我拥有的当前运行代码(基本上是一个玩具) - 不写任何东西,只是执行 - 是:

import java.applet.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dialog;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.io.BufferedWriter;

public class Runcommand3
{
  public static void main(String[] args) throws FileNotFoundException, IOException
  {
    //JApplet applet = new JApplet();
    //applet.init();

    final JFrame frame = new JFrame("Change Backlight");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    panel.setLayout(null);
    frame.add(panel);
    JButton button = new JButton("Click me to Run");
    button.setBounds(55,100,160,30);
    panel.add(button);

    frame.setSize(260,180);
    frame.setVisible(true);
    //This is an Action Listener which reacts to clicking on the button
    button.addActionListener(new ButtonHandler());
  }
}
 class ButtonHandler implements ActionListener{
                public void actionPerformed(ActionEvent event){
                double value = Double.parseDouble(
                JOptionPane.showInputDialog("please enter backlight value"));
                //File theFile = new File("thisfile.txt");
                //theFile.write(value);
                String command = "xbacklight -set " + value;
                try{Runtime run = Runtime.getRuntime();
                Process pr = run.exec(command);}
                catch(IOException t){t.printStackTrace();}
                  }
                }

In the above example how can I write 'value' to a file? Then, how can I add more input (more textfields)? Can I do it in the same class or I need more? My confusion comes (mainly but not only) from the fact that inside the ButtonHandler class I can NOT define any other objects (ie, open and write files etc).

在上面的示例中,如何将“值”写入文件?那么,如何添加更多输入(更多文本字段)?我可以在同一个班级做还是我需要更多?我的困惑来自(主要但不仅限于)在 ButtonHandler 类内部我不能定义任何其他对象(即打开和写入文件等)。

采纳答案by mario go

This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriterand FileWriter

这是我写入文件的方式。我会让您将此代码转换为您的 GUI 以供练习。查看有关BufferedWriterFileWriter 的更多信息

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

public class Files {

    public static void main(String args[]){

        System.out.print("Enter Text: ");
        Scanner scan = new Scanner(System.in);
        String text = scan.nextLine();
        FileWriter fWriter = null;
        BufferedWriter writer = null;
        try {
          fWriter = new FileWriter("text.txt");
          writer = new BufferedWriter(fWriter);
          writer.write(text);
          writer.newLine();
          writer.close();
          System.err.println("Your input of " + text.length() + " characters was saved.");
        } catch (Exception e) {
            System.out.println("Error!");
        }
    }

}

回答by snickers10m

For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:

对于您的第二个问题,您可能想考虑在 JFrame 上设置一个 JTextField,供用户输入行而不是 JOptionPane。它只是一个简单的文本框,您可以在每次按下按钮时将文本框的内容添加到文件中:

public static void main(String[] args) {
    JTextField myTextField = new JTextField();
    // Your code, set size and position of textfield
    panel.add(myTextField);
}

class ButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        String text = myTextField.getText();
        myTextField.setText("");
        new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
        // the rest of your code
    }
}