English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn different techniques to create strings from the content of a given file using Java.
Before creating a string from the file, we assume that insrcThere is a folder namedtest.txtfile.
This istest.txtcontent
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); } }
When running this program, the output is:
[This is a, Test file.]
In the above program, we use the user.dir property of System to get the current directory path stored in the variable. CheckJava program to get the current directory to getMore information.
We use defaultCharset() as the file encoding. If you know the encoding, please use it; otherwise, using the default encoding is safe
Then, we use the readAllLines() method to read all lines from the file. It accepts the file path and its encoding, and returns all lines in the form of a list, as shown in the output.
Since readAllLines may also throw IOException, we must define the main method in this way
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); } }
When running this program, the output is:
This is a Test file.
In the above program, we do not get a list of strings, but a single string containing all the content.
For this, we use the readAllBytes() method to read all bytes from the given path. Then we convert these bytes to a string using the default encoding.