在此程序中,您將學習使用Java從給定文件的內容創(chuàng)建字符串的不同技術。
從文件創(chuàng)建字符串之前,我們假設在src文件夾中有一個名為test.txt的文件。
這是test.txt的內容
This is a Test file.
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<String> 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
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.
在上面的程序中,我們得到的不是一個字符串列表,而是一個包含所有內容的字符串
為此,我們使用readAllBytes()方法從給定路徑讀取所有字節(jié)。然后使用默認編碼將這些字節(jié)轉換為字符串