Java 从 .txt 文件读取和显示数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/731365/
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
Reading and displaying data from a .txt file
提问by Jessy
How do you read and display data from .txt files?
如何从 .txt 文件读取和显示数据?
采纳答案by kevmo314
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
然后,您可以使用 in.readLine(); 一次读取一行。要读到最后,请编写一个 while 循环:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
回答by Jon Skeet
In general:
一般来说:
- Create a
FileInputStream
for the file. - Create an
InputStreamReader
wrapping the input stream, specifying the correct encoding - Optionally create a
BufferedReader
around theInputStreamReader
, which makes it simpler to read a line at a time. - Read until there's no more data (e.g.
readLine
returns null) - Display data as you go or buffer it up for later.
FileInputStream
为文件创建一个。- 创建一个
InputStreamReader
包装输入流,指定正确的编码 - 可以选择在
BufferedReader
周围创建一个InputStreamReader
,这样可以更轻松地一次读取一行。 - 读取直到没有更多数据(例如
readLine
返回空值) - 随时显示数据或将其缓冲以备后用。
If you need more help than that, please be more specific in your question.
如果您需要更多帮助,请在您的问题中更具体。
回答by jjnguy
If your file is strictly text, I prefer to use the java.util.Scanner
class.
如果您的文件是纯文本文件,我更喜欢使用java.util.Scanner
该类。
You can create a Scanner
out of a file by:
您可以通过以下方式创建Scanner
一个文件:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
然后,您可以使用以下方法从文件中读取文本:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
而且,您可以检查是否还有其他文本:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String
, you can print the string to the command line with:
阅读文本并将其保存到 . 后String
,您可以使用以下命令将字符串打印到命令行:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
发布的链接包含 Scanner 类的完整规范。帮助您完成您可能想做的其他事情将很有帮助。
回答by Craig Otis
You most likely will want to use the FileInputStream class:
您很可能希望使用 FileInputStream 类:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.
您还需要捕获 read() 方法和 FileInputStream 构造函数抛出的一些异常,但这些是特定于您的项目的实现细节。
回答by Vladimir
If you want to take some shortcuts you can use Apache Commons IO:
如果你想走一些捷径,你可以使用Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
:-)
回答by Greg Noe
I love this piece of code, use it to load a file into one String:
我喜欢这段代码,用它来将文件加载到一个字符串中:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\Z").next();
回答by Fenio
To read lines from .txt file with encoding UTF-8
:
使用以下命令从 .txt 文件中读取行encoding UTF-8
:
File krokiPath = new File("Records\Record");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(krokiPath), "UTF8"));
while((r = in.readLine()) != null) {
System.out.println(r);
}
in.close();
回答by chinni shaik
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
回答by Dylan Watson
In Java 8, you can read a whole file, simply with:
在 Java 8 中,您可以读取整个文件,只需:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
或者如果它是一个资源:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
回答by syam
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
下面是您可以尝试使用扫描仪类读取文件并在 java 中显示的代码。代码将从用户读取文件名并打印数据(记事本 VIM 文件)。
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
}