有时在处理文件时,我们需要在Java中读到String的文件,今天我们将研究如何在Java中读到String的文件。
Java 读取文件到 String
有很多方法来读到一个文件到 String 在Java. 我们将在本教程中探索以下方式。
- 使用 Java 读字符串使用 BufferedReader
- 使用 Java 读字符串使用 FileInputStream
- Java 读字符串使用 Files class
- 读字符串使用 Scanner class
- 读字符串使用 Apache Commons IO FileUt 类
Now let's look into these classes and read a file to String.
Java 使用 BufferedReader 读取文件到 String
我們可以使用「BufferedReader」的「readLine」方法來閱讀一行一行的檔案. 我們只需要將這些檔案附加到用 newline 字符的 StringBuilder對象中。
1BufferedReader reader = new BufferedReader(new FileReader(fileName));
2StringBuilder stringBuilder = new StringBuilder();
3String line = null;
4String ls = System.getProperty("line.separator");
5while ((line = reader.readLine()) != null) {
6 stringBuilder.append(line);
7 stringBuilder.append(ls);
8}
9// delete the last new line separator
10stringBuilder.deleteCharAt(stringBuilder.length() - 1);
11reader.close();
12
13String content = stringBuilder.toString();
有另一种有效的方式来读取文件到 String 使用 BufferedReader 和 [char array]( / 社区 / 教程 / string-to-char-array-to-string-java)。
1BufferedReader reader = new BufferedReader(new FileReader(fileName));
2StringBuilder stringBuilder = new StringBuilder();
3char[] buffer = new char[10];
4while (reader.read(buffer) != -1) {
5 stringBuilder.append(new String(buffer));
6 buffer = new char[10];
7}
8reader.close();
9
10String content = stringBuilder.toString();
使用 FileInputStream 读取 Java 中的 String 文件
我们可以使用 FileInputStream 和 byte array来读取文件到 String. 您应该使用此方法来读取非char 基于的文件,如图像,视频等。
1FileInputStream fis = new FileInputStream(fileName);
2byte[] buffer = new byte[10];
3StringBuilder sb = new StringBuilder();
4while (fis.read(buffer) != -1) {
5 sb.append(new String(buffer));
6 buffer = new byte[10];
7}
8fis.close();
9
10String content = sb.toString();
Java 读取文件以使用 File 类
我们可以使用 File 实用类来读取所有文件内容,以在一个代码行中串行。
1String content = new String(Files.readAllBytes(Paths.get(fileName)));
使用 Scanner 类读取文件到 String
扫描仪类是一种快速的方式来读取文本文件在Java中的字符串。
1Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
2String content = scanner.useDelimiter("\\A").next();
3scanner.close();
Java 读取文件以使用 Apache Commons IO FileUtils 类
如果您在项目中使用Apache Commons IO,那么这是一个简单而快速的方式来读取Java中的文件。
1String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);
Java 读取文件到 String 示例
这里是正确的 [例外处理]( / 社区 / 教程 / 例外处理-in-java)的最终程序,并显示所有不同的方法来读取文件。
1package com.journaldev.files;
2
3import java.io.BufferedReader;
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileReader;
7import java.io.IOException;
8import java.nio.charset.StandardCharsets;
9import java.nio.file.Files;
10import java.nio.file.Paths;
11import java.util.Scanner;
12
13import org.apache.commons.io.FileUtils;
14
15public class JavaReadFileToString {
16
17 /**
18 * This class shows different ways to read complete file contents to String
19 *
20 * @param args
21 * @throws IOException
22 */
23 public static void main(String[] args) {
24 String fileName = "/Users/pankaj/Downloads/myfile.txt";
25
26 String contents = readUsingScanner(fileName);
27 System.out.println("*****Read File to String Using Scanner*****\n" + contents);
28
29 contents = readUsingApacheCommonsIO(fileName);
30 System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents);
31
32 contents = readUsingFiles(fileName);
33 System.out.println("*****Read File to String Using Files Class*****\n" + contents);
34
35 contents = readUsingBufferedReader(fileName);
36 System.out.println("*****Read File to String Using BufferedReader*****\n" + contents);
37
38 contents = readUsingBufferedReaderCharArray(fileName);
39 System.out.println("*****Read File to String Using BufferedReader and char array*****\n" + contents);
40
41 contents = readUsingFileInputStream(fileName);
42 System.out.println("*****Read File to String Using FileInputStream*****\n" + contents);
43
44 }
45
46 private static String readUsingBufferedReaderCharArray(String fileName) {
47 BufferedReader reader = null;
48 StringBuilder stringBuilder = new StringBuilder();
49 char[] buffer = new char[10];
50 try {
51 reader = new BufferedReader(new FileReader(fileName));
52 while (reader.read(buffer) != -1) {
53 stringBuilder.append(new String(buffer));
54 buffer = new char[10];
55 }
56 } catch (IOException e) {
57 e.printStackTrace();
58 } finally {
59 if (reader != null)
60 try {
61 reader.close();
62 } catch (IOException e) {
63 e.printStackTrace();
64 }
65 }
66
67 return stringBuilder.toString();
68 }
69
70 private static String readUsingFileInputStream(String fileName) {
71 FileInputStream fis = null;
72 byte[] buffer = new byte[10];
73 StringBuilder sb = new StringBuilder();
74 try {
75 fis = new FileInputStream(fileName);
76
77 while (fis.read(buffer) != -1) {
78 sb.append(new String(buffer));
79 buffer = new byte[10];
80 }
81 fis.close();
82
83 } catch (IOException e) {
84 e.printStackTrace();
85 } finally {
86 if (fis != null)
87 try {
88 fis.close();
89 } catch (IOException e) {
90 e.printStackTrace();
91 }
92 }
93 return sb.toString();
94 }
95
96 private static String readUsingBufferedReader(String fileName) {
97 BufferedReader reader = null;
98 StringBuilder stringBuilder = new StringBuilder();
99
100 try {
101 reader = new BufferedReader(new FileReader(fileName));
102 String line = null;
103 String ls = System.getProperty("line.separator");
104 while ((line = reader.readLine()) != null) {
105 stringBuilder.append(line);
106 stringBuilder.append(ls);
107 }
108 // delete the last ls
109 stringBuilder.deleteCharAt(stringBuilder.length() - 1);
110 } catch (IOException e) {
111 e.printStackTrace();
112 } finally {
113 if (reader != null)
114 try {
115 reader.close();
116 } catch (IOException e) {
117 e.printStackTrace();
118 }
119 }
120
121 return stringBuilder.toString();
122 }
123
124 private static String readUsingFiles(String fileName) {
125 try {
126 return new String(Files.readAllBytes(Paths.get(fileName)));
127 } catch (IOException e) {
128 e.printStackTrace();
129 return null;
130 }
131 }
132
133 private static String readUsingApacheCommonsIO(String fileName) {
134 try {
135 return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);
136 } catch (IOException e) {
137 e.printStackTrace();
138 return null;
139 }
140 }
141
142 private static String readUsingScanner(String fileName) {
143 Scanner scanner = null;
144 try {
145 scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
146 // we can use Delimiter regex as "\\A", "\\Z" or "\\z"
147 String data = scanner.useDelimiter("\\A").next();
148 return data;
149 } catch (IOException e) {
150 e.printStackTrace();
151 return null;
152 } finally {
153 if (scanner != null)
154 scanner.close();
155 }
156
157 }
158
159}
您可以使用上述任何方法来读取文件内容的字符串在java. 但是,如果文件大小是巨大的,不建议,因为你可能会面临内存错误。
您可以从我们的 GitHub 存储库中查阅更多 Java IO 示例。
参考: