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

我已经将文件读入String。 该文件包含各种名称,每行一个名称。 现在问题是我想在String数组中使用这些名称。

为此我写了以下代码:

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

但是我没有得到所需的结果,并且在分割字符串后获得的数组长度为1.这意味着“fileString”没有“\ n”字符,但文件中有“\ n”字符。

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

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

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

 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(); } 

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

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

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

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

要么

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

此代码没有外部依赖项。 以下是如何使用具有正确资源和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); } } 

您可以将文件读入List而不是String ,然后转换为数组:

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

特别是我喜欢这个使用这里也描述的java.nio.file包。

  String content = new String(Files.readAllBytes(Paths.get("/path/to/file"))); 

很酷啊!

Java中没有可以读取整个文件的内置方法。 所以你有以下选择:

  • 使用非标准的库方法,例如Apache Commons ,请参阅romaintaz的答案中的代码示例。
  • 循环一些read方法(例如,读取字节的FileInputStream.read ,或读取字符的FileReader.read ;两者都读取到预分配的数组)。 这两个类都使用系统调用,因此如果您一次只读取少量数据(例如,小于4096字节),则必须使用bufering( BufferedInputStreamBufferedReader )加速它们。
  • 绕过BufferedReader.readLine 。 存在一个基本问题,它丢弃信息是否在文件末尾有'\n' – 因此例如它无法区分空文件和仅包含换行符的文件。

我用这个代码:

 // 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(); } } 

上面的代码具有以下优点:

  • 这是正确的:它读取整个文件,而不是丢弃任何字节。
  • 它允许您指定文件使用的字符集(编码)。
  • 它很快(无论文件包含多少个换行符)。
  • 它不会浪费内存(无论文件包含多少个换行符)。
 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; } 

我一直用这种方式:

 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(); 

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

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

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

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

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

如果只有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); 

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

您还可以使用java.nio.file.Files将整个文件读入字符串列表,然后将其转换为数组等。假设一个名为filePath的String变量,以下两行将执行此操作:

 List strList = Files.readAllLines(Paths.get(filePath), Charset.defaultCharset()); String[] strarray = strList.toArray(new String[0]); 

你可以试试Cactoos :

 import org.cactoos.io.TextOf; import java.io.File; new TextOf(new File("a.txt")).asString().split("\n")