如何在java中将文件读入字符串?

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

How to read a file into string in java?

java

提问by Yatendra Goel

I have read a file into a String. The file contains various names, one name per line. Now the problem is that I want those names in a String array.

我已将文件读入字符串。该文件包含各种名称,每行一个名称。现在的问题是我想要一个字符串数组中的这些名称。

For that I have written the following code:

为此,我编写了以下代码:

String [] names = fileString.split("\n"); // fileString is the string representation of the file

But I am not getting the desired results and the array obtained after splitting the string is of length 1. It means that the "fileString" doesn't have "\n" character but the file has this "\n" character.

但是我没有得到想要的结果,分割字符串后得到的数组长度为 1。这意味着“fileString”没有“\n”字符,但文件有这个“\n”字符。

So How to get around this problem?

那么如何解决这个问题呢?

采纳答案by b.roth

The problem is not with how you're splitting the string; that bit is correct.

问题不在于您如何拆分字符串;那一点是正确的。

You have to review how you are reading the file to the string. You need something like this:

您必须检查如何将文件读取到字符串。你需要这样的东西:

private String readFileAsString(String filePath) throws IOException {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

回答by leonm

You could read your file into a Listinstead of a Stringand then convert to an array:

您可以将文件读入 aList而不是 aString然后转换为数组:

//Setup a BufferedReader here    
List<String> list = new ArrayList<String>();
String line = reader.readLine();
while (line != null) {
  list.add(line);
  line = reader.readLine();
}
String[] arr = list.toArray(new String[0]);

回答by Martijn Courteaux

I always use this way:

我总是用这种方式:

String content = "";
String line;
BufferedReader reader = new BufferedReader(new FileReader(...));
while ((line = reader.readLine()) != null)
{
    content += "\n" + line;
}
// Cut of the first newline;
content = content.substring(1);
// Close the reader
reader.close();

回答by Romain Linsolas

What about using Apache Commons(Commons IOand Commons Lang)?

使用Apache Commons(Commons IOCommons Lang) 怎么样?

String[] lines = StringUtils.split(FileUtils.readFileToString(new File("...")), '\n');

回答by pts

There is no built-in method in Java which can read an entire file. So you have the following options:

Java 中没有可以读取整个文件的内置方法。因此,您有以下选择:

  • Use a non-standard library method, such as Apache Commons, see the code example in romaintaz's answer.
  • Loop around some readmethod (e.g. FileInputStream.read, which reads bytes, or FileReader.read, which reads chars; both read to a preallocated array). Both classes use system calls, so you'll have to speed them up with bufering (BufferedInputStreamor BufferedReader) if you are reading just a small amount of data (say, less than 4096 bytes) at a time.
  • Loop around BufferedReader.readLine. There has a fundamental problem that it discards the information whether there was a '\n'at the end of the file -- so e.g. it is unable to distinguish an empty file from a file containing just a newline.
  • 使用非标准库方法,例如Apache Commons,请参阅 romaintaz 答案中的代码示例。
  • 循环一些read方法(例如FileInputStream.read,读取字节,或FileReader.read读取字符;两者都读取到预先分配的数组)。这两个类都使用系统调用,因此如果您一次只读取少量数据(例如,小于 4096 字节),则必须通过缓冲 (BufferedInputStreamBufferedReader)来加速它们。
  • 循环BufferedReader.readLine。有一个基本问题,即它会丢弃'\n'文件末尾是否有 a 的信息——例如,它无法区分空文件和仅包含换行符的文件。

I'd use this code:

我会使用这个代码:

// charsetName can be null to use the default charset.
public static String readFileAsString(String fileName, String charsetName)
    throws java.io.IOException {
  java.io.InputStream is = new java.io.FileInputStream(fileName);
  try {
    final int bufsize = 4096;
    int available = is.available();
    byte[] data = new byte[available < bufsize ? bufsize : available];
    int used = 0;
    while (true) {
      if (data.length - used < bufsize) {
        byte[] newData = new byte[data.length << 1];
        System.arraycopy(data, 0, newData, 0, used);
        data = newData;
      }
      int got = is.read(data, used, data.length - used);
      if (got <= 0) break;
      used += got;
    }
    return charsetName != null ? new String(data, 0, used, charsetName)
                               : new String(data, 0, used);
  } finally {
    is.close();
  }
}

The code above has the following advantages:

上面的代码有以下优点:

  • It's correct: it reads the whole file, not discarding any byte.
  • It lets you specify the character set (encoding) the file uses.
  • It's fast (no matter how many newlines the file contains).
  • It doesn't waste memory (no matter how many newlines the file contains).
  • 这是正确的:它读取整个文件,不丢弃任何字节。
  • 它允许您指定文件使用的字符集(编码)。
  • 它很快(无论文件包含多少换行符)。
  • 它不会浪费内存(无论文件包含多少换行符)。

回答by Marcello Nuccio

As suggested by Garrett Rowe and Stan Jamesyou can use java.util.Scanner:

根据Garrett Rowe 和 Stan James 的建议,您可以使用java.util.Scanner

try (Scanner s = new Scanner(file).useDelimiter("\Z")) {
  String contents = s.next();
}

or

或者

try (Scanner s = new Scanner(file).useDelimiter("\n")) {
  while(s.hasNext()) {
    String line = s.next();
  }
}

This code does not have external dependencies.

此代码没有外部依赖项。

WARNING:you should specify the charset encoding as the second parameter of the Scanner's constructor. In this example I am using the platform's default, but this is most certainly wrong.

警告:您应该将字符集编码指定为 Scanner 构造函数的第二个参数。在这个例子中,我使用了平台的默认值,但这肯定是错误的。

Here is an example of how to use java.util.Scannerwith correct resource and error handling:

以下是如何使用java.util.Scanner正确资源和错误处理的示例:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Iterator;

class TestScanner {
  public static void main(String[] args)
    throws FileNotFoundException {
    File file = new File(args[0]);

    System.out.println(getFileContents(file));

    processFileLines(file, new LineProcessor() {
      @Override
      public void process(int lineNumber, String lineContents) {
        System.out.println(lineNumber + ": " + lineContents);
      }
    });
  }

  static String getFileContents(File file)
    throws FileNotFoundException {
    try (Scanner s = new Scanner(file).useDelimiter("\Z")) {
      return s.next();
    }
  }

  static void processFileLines(File file, LineProcessor lineProcessor)
    throws FileNotFoundException {
    try (Scanner s = new Scanner(file).useDelimiter("\n")) {
      for (int lineNumber = 1; s.hasNext(); ++lineNumber) {
        lineProcessor.process(lineNumber, s.next());
      }
    }
  }

  static interface LineProcessor {
    void process(int lineNumber, String lineContents);
  }
}

回答by kiran

FileReader fr=new FileReader(filename);
BufferedReader br=new BufferedReader(fr);
String strline;
String arr[]=new String[10];//10 is the no. of strings
while((strline=br.readLine())!=null)
{
arr[i++]=strline;
}

回答by bancer

The simplest solution for reading a text file line by line and putting the results into an array of strings without using third party libraries would be this:

逐行读取文本文件并将结果放入字符串数组而不使用第三方库的最简单解决方案是:

ArrayList<String> names = new ArrayList<String>();
Scanner scanner = new Scanner(new File("names.txt"));
while(scanner.hasNextLine()) {
    names.add(scanner.nextLine());
}
scanner.close();
String[] namesArr = (String[]) names.toArray();

回答by Anoyz

A simpler (without loops), but less correctway, is to read everything to a byte array:

一种更简单(没有循环)但不太正确的方法是将所有内容读入字节数组:

FileInputStream is = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];  
is.read(b, 0, (int) file.length());
String contents = new String(b);

Also note that this has serious performance issues.

另请注意,这具有严重的性能问题。

回答by Sae762

If you have only InputStream, you can use InputStreamReader.

如果您只有 InputStream,则可以使用 InputStreamReader。

SmbFileInputStream in = new SmbFileInputStream("smb://host/dir/file.ext");
InputStreamReader r=new InputStreamReader(in);
char buf[] = new char[5000];
int count=r.read(buf);
String s=String.valueOf(buf, 0, count);

You can add cycle and StringBuffer if needed.

如果需要,您可以添加循环和 StringBuffer。