Java 17 Recipes


-2. Reading the Contents of Files


Download 3.2 Mb.
Pdf ko'rish
bet33/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   29   30   31   32   33   34   35   36   ...   245
Bog'liq
Java 17 Recipes

2-2. Reading the Contents of Files
 Problem
You want to read the contents of a file.
 Solution
Use the java.nio.file.Files class, which provides static methods operating on files 
and directories (see Listing 
2-2
).
Listing 2-2. Reading Content of File
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
class ReadContentsFile
{
public static void main(String[] args)
{
Path filePathHello = Paths.get("C:/hello.txt");
try
{
String contents = Files.readString(filePath filePathHello);
System.out.println(contents);
}
Chapter 2 enhanCements from Java 9 through Java 17 


52
catch (IOException err)
{
err.printStackTrace();
}
}
}
The following is the output.
Ciao da
Luciano Manelli
Taranto
ITALY
This is the content of a text file on the author’s computer.
 How It Works
Java 11 included some new Files class methods to read content from a file.
The Files.readString(Path) method reads characters from a file, accepts the file’s 
path, and returns a string with the file’s contents. It throws an IOException if an error 
occurs. The used charset for the decoding is the UTF-8.
You can also use the Files.readString(Path, Charset) method. It is used for 
using a specific charset to decode bytes to characters. It reads from the file and throws 
an IOException. The Files.readString(Path) method is equal to readString(path, 
StandardCharsets.UTF_8).
Listing 
2-3
 is an example.
Listing 2-3. Reading the File Content with charset
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
Chapter 2 enhanCements from Java 9 through Java 17 


53
public class Main
{
public static void main(String[] args)
{
Path filePathHello = Paths.get("C:/hello.txt");
try
{
String contents = Files.readString(filePath filePathHello, 
StandardCharsets.UTF_8);
System.out.println(contents);
}
catch (IOException err)
{
err.printStackTrace();
}
}
}

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   29   30   31   32   33   34   35   36   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling