如何从用户获取输入并将其保存到文本文件中 [英] how to get input from the user and save that into a text file

查看:76
本文介绍了如何从用户获取输入并将其保存到文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里得到输入。

输入20行。

想要将其保存在一个文本文件中。

每行应该在一个新行中出现。

就是这样。

谢谢。

I want to get input from user.
input of 20 lines.
want to save it in a text file.
every line should occur in a new line.
thats it.
thanks.

推荐答案

你应该从这个文档 [ ^ ]。



仍然,



使用扫描仪获取输入并执行以下操作,

You should take a help from this documentation[^].

Still,

get the input using Scanner and do the following,
try {
 
			String content = "This is the content to write into file";
// get you content here using Scanner
 
			File file = new File("C:/file1.txt");
 
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
 
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
 
			System.out.println("Done");
 
		} catch (IOException e) {
			e.printStackTrace();
		}



-KR


-KR


在C中你有stdio.h,它包含所有标准的io功能:

在您的场景中,您需要:

printf()将输出写入屏幕。

scanf()从键盘读取输入。

对于文件操作,您需要更多步骤:

In C you have stdio.h which contains all standard io functionality:
In your scenario you would require:
printf() to write output to the screen.
scanf() to read input from keyboard.
For file operations you require a couple more steps:
FILE *myfile;
myfile = fopen("myfile.txt", "w"); // or r, a, r+, w+, a+
fprintf(myfile, "Whatever...\n");
fclose(myfile); // always


Resp Person,

程序接受20行,以更改换行循环次数。

按下回车键后,该行会写入文件。



-----------------试试这段代码-----------------------

Resp Person,
Program Accept 20 lines, to change line change loop count.
After press enter button, that line gets write to file.

-----------------Try This code-----------------------
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Demo 
{
	public static void main(String[] args) 
	{
		try 
		{
		      //create a buffered reader that connects to the console
		      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		      //create an print writer for writing to a file
		      PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
		      		      
		      for(int i =0; i < 20; i++)		      		     
			      //output to the file a line
		    	  out.println(in.readLine());
		      
		      //close the file (VERY IMPORTANT!)
		      out.close();
		   }
		   catch(IOException e1) 
		   {
		        System.out.println("Error during reading/writing");
		   }
	}
}


这篇关于如何从用户获取输入并将其保存到文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆