How to Create String from Contents of a File in Java Program
Java Strings
- A Java object that represents a string of characters is called a string. Strings are frequently employed to store text data like names, addresses, words, etc. A String class that comes with Java offers methods for comparing and manipulating strings.
- Strings can be compared for equality using the equals method. For example, “Hello”.equals(“Hello”) returns true. Note that the == operator compares the memory addresses of two objects, not their values. To compare the values of two strings, use the equals method.
To know more about Java Program to Create string From Contents of a file, read the complete article.
Steps to Create String from Contents of a File in Java Program
- To create String from Contents of a file in java program, you can follow these steps:
- Import the Required Libraries.
- Create a File object to represent the file:
- Read the contents of the file into a byte[]:
- Convert the byte[] to a string using the desired encoding.
- Use the contents string as needed in the rest of your program.
Java String :
Java has a special memory area called the string pool, where string objects are stored. If two strings have the same value, only one object will be created and stored in the string pool.
Java File Class :
The file or directory in the file system is represented by the java.io.File class. It offers numerous ways to operate with files and directories, including the ability to create, delete, and rename files as well as check to see if a file or directory already exists.
Let’s look at a Java Program to Create String from Contents of a file to perform certain operations.
Example 1: Java Program to Create String from Contents of a file.
Run
import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) { try { File file = new File("path/to/file"); byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath())); String contents = new String(encoded, StandardCharsets.UTF_8); System.out.println(contents); } catch (IOException e) { System.out.println("PrepInsta: " + e.getMessage()); } } }
Output
PrepInsta: /home/path/to/file
NOTE: Make sure to replace "path/to/file" with the actual file path on your system
Explanation:
In this Example, the file is represented by a File object and its contents are read into a byte[] using the readAllBytes method from the Files class. The contents of the file are then converted to a string using the String constructor and the desired encoding (UTF-8 in this case). Finally, the contents of the string are printed to the console.
Example 2 : Java Program to Create String from Contents of a file.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("path/to/file")); StringBuilder builder = new StringBuilder(); String line = reader.readLine(); while (line != null) { builder.append(line); builder.append(System.lineSeparator()); line = reader.readLine(); } String contents = builder.toString(); System.out.println(contents); reader.close(); } catch (IOException e) { System.out.println("An error occurred while reading the file: " + e.getMessage()); } } }
Output
An error occurred while reading the file: path/to/file (No such file or directory)
NOTE: Make sure to replace "path/to/file" with the actual file path on your system
Explanation:
A BufferedReader is used for reading the contents of the file.
The contents are appended to a StringBuilder object with a line separator.
The contents of the StringBuilder are converted to a string and printed to the console.
Example 3: Java Program Create String from contents of a file
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class Main { public static void main(String[] args) { try { String contents = new String(Files.readAllBytes(Paths.get("path/to/file"))); System.out.println(contents); } catch (IOException e) { System.out.println("Prepinsta Prime: " + e.getMessage()); } } }
Output
Prepinsta Prime: path/to/file
NOTE: Make sure to replace "path/to/file" with the actual file path on your system
Explanation:
The contents of the file are read into a byte array using the readALLBytes method from the Files class.
The contents are then converted to a string using the String Constructor.
The contents of the string are printed to the console.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment