从文件创建字符串之前,我们假设在src文件夹中有一个名为test.txt的文件。
这是test.txt的内容
This is a
Test file.
示例1:从文件创建字符串
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class FileString {
public static void main(String[] args) throws IOException {
String path = System.getProperty("user.dir") + "\\src\\test.txt";
Charset encoding = Charset.defaultCharset();
List lines = Files.readAllLines(Paths.get(path), encoding);
System.out.println(lines);
}
}
输出
[This is a, Test file.]
在上面的程序中,我们使用System
的user.dir
属性获取存储在变量path中的当前目录。检查Java程序以获取当前目录以获取更多信息。
我们使用defaultCharset()
作为文件的编码。如果您知道编码,请使用它,否则使用默认编码是安全的。
然后,我们使用readAllLines()
方法从文件中读取所有行。它采用文件的路径及其编码 ,并将所有行作为列表返回,如输出所示。
由于readAllLines
也可能会引发IOException,因此我们必须这样定义main方法
public static void main(String[] args) throws IOException
示例2:从文件创建字符串
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileString {
public static void main(String[] args) throws IOException {
String path = System.getProperty("user.dir") + "\\src\\test.txt";
Charset encoding = Charset.defaultCharset();
byte[] encoded = Files.readAllBytes(Paths.get(path));
String lines = new String(encoded, encoding);
System.out.println(lines);
}
}
输出
This is a
Test file.
在上面的程序中,我们没有得到字符串的列表,而是得到了一个包含所有内容的字符串, lines 。
为此,我们使用readAllBytes()
方法从给定路径读取所有字节。然后,使用默认编码将这些字节转换为字符串 。