在java中读取文本文件

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

Reading a text file in java

javafile-io

提问by

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.

当每一行都包含整数、字符串和双精度数时,我将如何在 Java 中读取 .txt 文件并将每一行放入一个数组中?每行都有不同数量的单词/数字。

I'm a complete noob in Java so sorry if this question is a bit stupid.

我是 Java 的完全菜鸟,如果这个问题有点愚蠢,我很抱歉。

Thanks

谢谢

回答by Valentin Rocher

Your question is not very clear, so I'll only answer for the "read" part :

你的问题不是很清楚,所以我只回答“阅读”部分:

List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
    lines.add(line);
    line = br.readLine();
}

回答by Aaron Digulla

Try the Scannerclass which no one knows about but can do almost anything with text.

尝试一下Scanner没人知道但几乎可以用文本做任何事情的课程。

To get a reader for a file, use

要获取文件的阅读器,请使用

File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
    new FileInputStream (file), encoding));

... use reader ...

reader.close ();

You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.

您应该真正指定编码,否则当您遇到变音符号、Unicode 等时会得到奇怪的结果。

回答by Alasdair

Easiest option is to simply use the Apache Commons IOJAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;

最简单的选择是简单地使用Apache Commons IOJAR 并导入 org.apache.commons.io.FileUtils 类。使用这个类有很多可能性,但最明显的是如下;

List<String> lines = FileUtils.readLines(new File("untitled.txt"));

It's that easy.

就这么简单。

"Don't reinvent the wheel."

“不要重新发明轮子。”

回答by Kamil

Common used:

常用:

    String line = null;
    File file = new File( "readme.txt" );

    FileReader fr = null;
    try
    {
        fr = new FileReader( file );
    } 
    catch (FileNotFoundException e) 
    {  
        System.out.println( "File doesn't exists" );
        e.printStackTrace();
    }
    BufferedReader br = new BufferedReader( fr );

    try
    {
        while( (line = br.readLine()) != null )
    {
        System.out.println( line );
    }

回答by NikhilP

@user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.

@user248921 首先,您可以在字符串数组中存储任何内容,因此您可以创建字符串数组并在数组中存储一行,并在需要时在代码中使用值。您可以使用以下代码在数组中存储异构(包含字符串、整数、布尔值等)行。

public class user {
 public static void main(String x[]) throws IOException{
  BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
  String[] user=new String[500];
  String line="";
  while ((line = b.readLine()) != null) {
   user[i]=line; 
   System.out.println(user[1]);
   i++;  
   }

 }
}

回答by Babofett

This is a nice way to work with Streams and Collectors.

这是使用流和收集器的好方法。

List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
    myList = reader.lines() // This will return a Stream<String>
                 .collect(Collectors.toList());
}catch(Exception e){
    e.printStackTrace();
}

When working with Streams you have also multiple methods to filter, manipulate or reduce your input.

使用 Streams 时,您还有多种方法来过滤、操作或减少您的输入。

回答by Johnny

The best approach to read a file in Javais to open in, read line by line and process it and close the strea

读入文件的最佳方法Java是打开,逐行读取并处理它并关闭流

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console - do what you want to do
  System.out.println (strLine);
}

//Close the input stream
fstream.close();

To learn more about how to read file in Java, check out the article.

要了解有关如何在 Java 中读取文件的更多信息,请查看文章