Java 将多个用户输入保存到一个文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19860583/
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-12 20:46:51  来源:igfitidea点击:

Saving multiple user inputs to a text file

javafile-ioinput

提问by family2dyl

Firstly I must apologize if this has already been explained... While I have done searches to find an answer to my problem, I am still very new when it comes to Java so I couldn't really understand. (I've only been learning Java for a couple of days.)

首先,如果这已经被解释了,我必须道歉......虽然我已经进行了搜索以找到我的问题的答案,但我对 Java 仍然很陌生,所以我无法真正理解。(我只学习了几天 Java。)

My friend, who is trying to teach me Java sets me assignments that I have to complete and I'm supposed to learn what I need to do to complete these assignments myself. Recently he gave me the challenge of creating a program that asks the user for their name, age and a username. This program then needs to output these in a sentence. That part is easy. What I'm having difficulty with is the next part where I have to make the program save these to a file, along with any future inputs from a user.

我的朋友,他试图教我 Java 给我安排了我必须完成的作业,我应该学习我自己需要做什么来完成这些作业。最近,他给了我一个挑战,即创建一个程序,询问用户的姓名、年龄和用户名。这个程序然后需要在一个句子中输出这些。那部分很容易。我遇到的困难是下一部分,我必须让程序将这些保存到文件中,以及来自用户的任何未来输入。

Here's what I have:

这是我所拥有的:

import java.util.Scanner;

public class easy1 
{

@SuppressWarnings("resource")
public static void main(String[] args)
{
    System.out.println("Enter your name, age and username: ");
    Scanner sc = new Scanner(System.in);

    String name = sc.next(), age = sc.next(), user = sc.next();

    System.out.println("Your name is " + name + ", you are " + age + " years old, and your username is " + user + ".");
}
}

I'm not really looking for anybody to tell me what to do, what I would appreciate is just a little guidance or a clue as to what I should be doing. If you do give me an answer then an explanation of how it works would be nice.

我并不是真的在寻找任何人来告诉我该做什么,我希望得到的只是关于我应该做什么的一点指导或线索。如果你确实给了我一个答案,那么解释它是如何工作的会很好。

Thank you.

谢谢你。

采纳答案by Paul Samsotha

To save to file you need to create a Fileobject.

要保存到文件,您需要创建一个File对象。

File file = new File("someFile.txt");   -- takes file name as argument.  

Then you need a way to print to the file. You can use PrintWriter

然后您需要一种打印到文件的方法。您可以使用PrintWriter

PrintWriter writer = new PrintWriter(file);  -- takes file as argument.

To write to the file, just use the PrintWriter write()method

要写入文件,只需使用该PrintWriter write()方法

writer.write(name);

If you're only in your second day of learning, tell your friend it's too early to be learning about I/O (input/output). You should be learning about loops, arrays, methods, operators, if/else if statements, Strings, etc. All the basics. Once you've finished the basics, you're ready to get into Object Oriented Programming (OOP). That's where the real magic happens. So take time to learn the basics, so you'll be ready for the deeper stuff.

如果你只是在学习的第二天,告诉你的朋友现在学习 I/O(输入/输出)还为时过早。您应该了解loops, arrays, methods, operators, if/else if statements, Strings, etc. 所有的基础知识。完成基础知识后,您就可以进入面向对象编程 (OOP) 了。这就是真正的魔法发生的地方。所以花点时间学习基础知识,这样你就可以为更深层次的东西做好准备。

Pick up a comprehensive book. I'd recommend a textbook Introduction to Java Programming by Daniel liang

拿起一本综合性的书。我推荐一本教科书Introduction to Java Programming by Daniel liang

回答by MadConan

You need to tap into java.io.Fileand java.io.FileOutputStream(or java.io.FileWriter). Start here. It will look something like this (*this is not complete -- you'll need exception handling! *)

您需要点击java.io.Filejava.io.FileOutputStream(或java.io.FileWriter)。从这里开始。它看起来像这样(*这不完整——你需要异常处理!*)

String input = getInput();
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("myFile")));
writer.write(input,0,input.length());
writer.close();

I can't say this enough: Read the API :)

我不能这么说:阅读 API :)

回答by Ray Stojonic

You'll need to open an output file and write to it.

您需要打开一个输出文件并写入其中。

Probably the easiest way to do this is to use a PrintStream, which you'll be familiar with using as System.outis a PrintStream.

可能最简单的方法是使用 a PrintStream,您将熟悉使用 as System.outis a PrintStream

Assuming you're using Java 7:

假设您使用的是 Java 7:

try( PrintStream out = new PrintStream( new File( "output.txt" ) ) ) {
    out.println( stuff );
}

By using the try-with-resources block, the PrintStreamand Fileare automatically closed for you after you're done writing. edit: and you'll already have the tryin place to handle the FileNotFoundExceptionthat PrintStream( File )says it may throw.

通过使用 try-with-resources 块,PrintStreamFile会在您完成编写后自动关闭。编辑:你就已经拥有了try到位处理FileNotFoundExceptionPrintStream( File )说,它可能会抛出。

回答by Paul Vargas

The simplest way is:

最简单的方法是:

try (
    PrintWriter out = new PrintWriter("output.txt", "UTF-8");
    Scanner sc = new Scanner(System.in);
) {

    // Read input using sc

    // Output to out, e.g.
    out.println("Your name is " + name + ".");

} catch(IOException e) {
    // Manage the exception
}