Write a Java Program to Create String from Contents of a File

Java Program to Create String from Contents of a File

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Create String from Contents of a File
Java Program to Create String from Contents of a File

Write a Java Program to Create String from Contents of a File

PROGRAM: Java Program to Create String from Contents of a File

/*Java Program to Create String from Contents of a File*/

 1: Create String from 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);
}
}

2: Create String from a file

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);
}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *