How To Read A Text File As String In Java? Example - Java67
Maybe your like
Pages
- Home
- core java
- spring
- online courses
- thread
- java 8
- coding
- sql
- books
- oop
- interview
- certification
- free resources
- best
Reading a Text File as String in Java - Files.readAllBytes() Example
This is the standard way to read the whole file as String in Java. Just make sure the file is small or medium-size and you have enough heap space to hold the text from a file into memory. If you don't have enough memory, the below code can throw java.lang.OutOfMemoryError: Java heap space, so beware of that. Here is the method to read a file as String in Java 7: public static String readFileAsString(String fileName) { String text = ""; try { text = new String(Files.readAllBytes(Paths.get("file.txt"))); } catch (IOException e) { e.printStackTrace(); } return text; } You should also be careful with character encoding. The above code assumes that the file and platform's default character encoding are the same. If that's not the case then use the correct character encoding while converting byte array to String in Java. See these free Java Programming online courses to learn more about character encoding and converting bytes to text in Java.
Reading Text File as String in Java - BufferedReader Example
This was the old way of reading a file as String in Java. You can see that it requires almost 8 to 10 lines of code, which can now effectively be done in just one line in Java 7. It uses the readLine() method to read the file line by line and then joined them together using StringBuilder's append() method. BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line).append("\n"); line = br.readLine(); } String fileAsString = sb.toString(); Don't forget to append the \n character to insert the line break, otherwise, all lines will be joined together and all text from the file will come as just one big line. If you are not familiar with \n or \r\n, I suggest you join a comprehensive Java course The Complete Java Masterclass to learn more about special characters in Java.Java Program to read a text file as String
Here is the complete Java program to read a text file as String, it includes both JDK 6 and JDK 7 approaches to reading the content of the file in a string variable. import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /* * Java Program read a text file as String * first by using the JDK 7 utility method Files.readAllBytes() * and second by using BufferedReader and StringBuilder. */ public class ReadFileAsString { public static void main(String[] args) throws Exception { // read whole file as String in JDK 7 String data = ""; try { data = new String(Files.readAllBytes(Paths.get("file.txt"))); } catch (IOException e) { e.printStackTrace(); } System.out.println("Text file as String in Java"); System.out.println(data); // read file as String in Java SE 6 and lower version BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line).append("\n"); line = br.readLine(); } String fileAsString = sb.toString(); System.out .println("whole file as String using BufferedReader and StringBuilder"); System.out.println(fileAsString); br.close(); } } Output Text file as String in Java Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers. whole file as String using BufferedReader and StringBuilder Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers. In the second example, don't forget to append the "\n" or "\r\n" depending upon whether you are running on Windows or UNIX, otherwise, all lines of files are concatenated into just one line. Also, don't forget to close the BufferedReader to prevent resource leaks, especially when you are not using the automatic resource management feature of Java 7. That's all about how to read a text file as String in Java. You can use the new way if your program is running on JRE 7 and the old way if you are using Java 6 or lower versions. Pay attention to the character encoding of the file if you are not sure whether both file and platform's default character encoding (the machine where your Java program is running) is not the same. Related Java File tutorials you may like- How to write to a file using BufferedWriter in Java? (solution)
- How to read/write an XLSX file in Java? (solution)
- How to read a text file using BufferedReader in Java? (example)
- How to load data from a CSV file in Java? (example)
- How to append text to a file in Java? (solution)
- How to read InputStream as Stream in Java? (example)
- How to find the highest occurring word from a file in Java? (solution)
- 2 ways to read a text file in Java? (solution)
5 comments:
UnknownAugust 20, 2016 at 3:01 AMidk how to solve the path.get error of this programme though i tried with Paths.get method using a Paths.get method is of URI so it is giving me compilation error.it's showing me "The method get(String) is undefined for the type Path".so,[ please help me with that.
ReplyDeleteReplies- Reply
UnknownApril 20, 2020 at 11:03 AMGod bless you, I am facing this problem since last week. But you solve my problem. I am very happy now. Thanks
ReplyDeleteReplies
javin paulApril 22, 2020 at 5:08 AMThank you, I appreciate your kind words
DeleteReplies- Reply
Reply
UnknownApril 20, 2020 at 11:15 AMSir but how can I read Int values it shows aski values
ReplyDeleteReplies
javin paulApril 22, 2020 at 5:08 AMCan you give more detail? may be share the code you are using to read the int, that can help
DeleteReplies- Reply
Reply
Feel free to comment, ask questions if you have any doubt.
Newer Post Older Post Home Subscribe to: Post Comments (Atom)Recommended Courses
- best python courses
- best java courses
- system design courses
- best spring courses
- best hibernate courses
- best design pattern courses
- best Linux courses
- best JavaScript courses
- best data structure and algorithms courses
- Best Multithreading Courses
- best MERN stack courses
- Best Git courses
- Best Microservice Courses
- Best DevOps Courses
- best MEAN stack Courses
- free Java courses
- free DSA courses
- free sql courses
- free Linux courses
- Free Docker courses
- free JUnit courses
Java File Tutorial
- File - Empty Check
- File - Best Practices
- File - Locking
- File - Scanner
- File - ZipEntry
- File - Copy
- File - Read as String
- File - BufferedReader
- File - to ArrayList
- File - BufferedReader vs Scanner
- File - FileReader vs FileInputStream
- File - CSV Loader
- File - Append Text
- File - BufferedWriter
- File - Reading Text
- File - InputStream to String
- File - Create
- File - Password
- File - FileInputStream + BufferedReader
String Tutorials
- string - 101 guide
- string - contains
- string - check unique
- string - rotation
- string - count words
- string - join
- string - substring
- string - split
- string - palindrome
- string - reverse words
- string - byte array
- string - to enum
- string - compare
- string - empty
- string - stringbuffer
- string - duplicate
- string - immutable
- string - split regex
- string - remove whitespace
- string - toLowerCase
- string - reverse
Categories
- .NET
- abstract class
- Affiliate marketing
- After Effects
- Agile
- AI Tools
- Amazon Web Service
- android
- Angular
- Anonymous class
- Ansible
- apache camel
- Apache kafka
- Apache spark
- app development
- array
- ArrayList
- Artificial Intelligence
- automation
- aws
- aws certification
- Azure Certifications
- backend development
- bash
- basics
- beginners
- best of java67
- best practices
- Big Data
- binary tree
- bit manipulation
- black friday deals
- Blockchain
- BlockingDeque
- books
- Bootstrap
- business analysis
- ByteByteGo
- C programming
- C++
- Career
- ChatGPT
- Chef
- cloud certification
- Cloud Computing
- Code Example
- Code Review
- codecademy
- Codemia
- CodeRabbit
- coding
- coding exercise
- Coding Interview
- Coding Problems
- Comparator
- computer science
- Computer Vision
- concurrency tutorial
- ConcurrentHashMap
- core java
- core java interview question answer
- course review
- Coursera
- courses
- crontab
- CSS
- Cyber Monday
- Cyber Security
- Data Analysis
- data science
- data structure and algorithm
- Data Visualization
- database
- datacamp
- date and time
- debugging
- deep learning
- default methods
- design pattern
- DevOps
- DevSecOps
- Distributed Systems
- Django
- docker
- double
- Drawing
- dyanmic programming
- dynamic Programming
- eBooks
- Eclipse
- EJB
- enum
- equals
- error and exception
- Ethical hacking
- Excel
- exception
- Exponent
- expressjs
- FAANG
- Figma
- Firebase
- flatmap
- float
- Flutter
- free resources
- freelancing
- Frontend Masters
- fun
- Fundamental
- fundamentals
- Game development
- garbage collection
- general
- Generics
- gifts
- git and github
- golang
- Google Cloud Certification
- Google Cloud Platform
- Gradle
- grails
- graph
- graphic design
- grep
- Groovy
- gRPC
- Hadoop
- HashMap
- HashSet
- haskell
- Hibernate
- Hibernate interview Question
- homework
- HTML
- HTTP
- HttpClient
- i
- interface
- Internet of Things (IoT)
- interview
- interview questions
- IT Certification
- J2EE
- Jackson
- java
- Java 5 tutorial
- java 7
- Java 8
- java 9
- java basics
- Java Certification
- Java collection tutorial
- java concurrency tutorial
- java design pattern
- Java Enum
- Java file tutorials
- Java Functional Programming
- Java Installation Guide
- Java Interview Question
- Java interview questions
- Java IO interview question
- java io tutorial
- java map tutorials
- java modules
- Java Multithreading Tutorial
- Java networking tutorial
- Java Operator tutorial
- Java programming Tutorial
- Java String tutorial
- Java7
- JavaScript
- JavaScript Interview Question
- JavaScript Tutorial
- JDBC
- JEE Interview Questions
- Jenkins
- JMS
- JPA
- jQuery
- JSON
- JSP
- JSP Interview Question
- JSTL
- JUnit
- JVM
- Keras
- keystore
- Kotlin
- kubernetes
- lambda expression
- Laraval
- learning
- linked list
- Linux
- Log4j
- logging
- Lombok
- LSAT
- Mac OS X
- machine learning
- Mathematics
- Matlab
- Maven
- MERN stack
- Messaging
- Microservices
- Microsoft
- Microsoft Azure Platform
- Microsoft Excel
- Microsoft Power BI
- Mockito
- MongoDB
- MysQL
- MySQL tutorial example
- nested class
- neural network
- Next.js
- NFT
- NLP
- Node.js
- nslookup
- object oriented programming
- OCAJP
- OCMJEA
- OCPJP
- offers
- Oracle
- Perl
- personal development
- Photoshop
- PHP
- pluralsight
- PostgerSQL
- postman
- Powerpoint
- programmers
- programming
- programming problems
- Project Management
- projects
- Prompt Engineering
- Python
- Pytorch
- Quarkus
- questions
- Queue
- R programming
- React
- React Hooks
- react native
- Record
- Recursion
- Redux
- regular expression example
- REST tutorials
- Review
- RoadMap
- Ruby
- Salesforce
- SAT
- Scala
- Scala Interview Questions
- Scanner
- scripting
- Scrum
- Scrum Master Certification
- Selenium
- SEO
- Serialization
- Servlet
- Servlet Interview Questions
- Set
- shell scripting
- smart contracts
- Snowflake SnowPro Certification
- soft link
- soft skills
- software architecture
- Solaris
- Solidity
- Sorting Algorithm
- Spark
- spring boot
- Spring Certification
- spring cloud
- spring data jpa
- spring framework
- spring interview question
- spring mvc
- spring security
- sql
- SQL interview Question
- SQL Joins
- SQL SERVER
- ssl
- Static
- Statistics
- Stream
- String
- Struts
- Swift
- swing
- switch case
- system design
- Tableau
- Tailwind
- TensorFlow
- ternary operator
- testing
- thread
- thread interview questions
- Time series analysis
- Tips
- tomcat
- tools
- tree
- TreeMap
- troubleshooting
- TypeScript
- Udacity
- Udemy
- UI and UX Design
- UML
- unit testing
- Unity 3D
- Unix
- unreal engine
- Video Editing
- Vuejs
- web design
- web development
- web scrapping
- Web Service
- Whizlabs
- Wix
- xml
- YAML
- ZTM Academy
Best System Design and Coding Interview Resources
System Design & Interview Prep
- ByteByteGo Lifetime Plan (50% OFF)
- Codemia Lifetime Plan (60% OFF)
- Exponent Annual Plan (70% OFF)
- Educative Premium Plus (55% OFF)
- DesignGurus All Course Bundle (55% OFF)
- Everything Java Interview Bundle (50% OFF)
- 101 Blockchain (50% OFF)
- Vlad Mihalcea's High Performance Bundle (50% OFF)
- Javarevisited Substack Subscription (50% OFF)
- Head First Software Architecture (Book)
Search This Blog
Best Online Learning Resources and Platforms
- Coursera Plus (40% OFF)
- Datacamp Sale (50% OFF)
- AlgoMonster Lifetime Plan (50% OFF)
- Udemy Sale (80% OFF)
- Baeldung (33% OFF)
- LabEx Sale (50% OFF)
- Codecademy Sale (60% OFF)
- Udacity Sale (50% OFF)
- ZTM Academy Sale (66% OFF)
- Frontend Masters Deal
- Whizlabs Deal (70% OFF)
Javarevisited
Loading...Spring Interview Prep List
- Spring Boot Interview questions
- Spring Cloud Interview questions
- Spring MVC Interview Questions
- Microservices Interview questions
- 10 Spring MVC annotations
- Spring Boot Courses
- Spring Framework Courses
Subscribe for Discounts and Updates
FollowInterview Questions
- core java interview questions
- SQL interview questions
- data structure interview question
- coding interview questions
- java collection interview questions
- java design pattern interview questions
- thread interview questions
- hibernate interview questions
- j2ee interview questions
- Spring Interview Questions
- object oriented programming questions
Followers
Blog Archive
- ► 2025 (554)
- ► December (3)
- ► November (9)
- ► October (72)
- ► September (18)
- ► July (71)
- ► June (103)
- ► May (67)
- ► April (25)
- ► March (18)
- ► February (79)
- ► January (89)
- ► 2023 (380)
- ► December (1)
- ► November (2)
- ► October (4)
- ► September (154)
- ► August (12)
- ► July (23)
- ► May (9)
- ► April (116)
- ► March (15)
- ► February (35)
- ► January (9)
- ► 2022 (164)
- ► December (18)
- ► October (1)
- ► September (1)
- ► August (45)
- ► July (27)
- ► June (11)
- ► May (19)
- ► April (16)
- ► March (12)
- ► February (6)
- ► January (8)
- ► 2021 (104)
- ► December (6)
- ► November (2)
- ► October (13)
- ► September (18)
- ► August (31)
- ► July (34)
- ► 2020 (10)
- ► August (2)
- ► July (1)
- ► June (1)
- ► April (3)
- ► March (1)
- ► February (2)
- ► 2019 (9)
- ► December (1)
- ► November (1)
- ► October (1)
- ► September (1)
- ► July (1)
- ► June (1)
- ► April (3)
- ► 2018 (9)
- ► November (1)
- ► April (8)
- ► 2017 (4)
- ► October (1)
- ► September (2)
- ► April (1)
- ► 2015 (8)
- ► July (1)
- ► June (1)
- ► May (1)
- ► February (5)
- ► 2012 (1)
- ► September (1)
Privacy
- Privacy Policy
- Terms & Conditions
Popular Posts
- 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
- How to fix "illegal start of expression" error in Java? Example
- Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
- 5 Examples of Formatting Float or Double Numbers to String in Java
- Top 10 Frequently asked SQL Query Interview Questions Answers
Subscribe
Get new posts by email:
SubscribeTag » How To Read The Text File In Java
-
Different Ways Of Reading A Text File In Java - GeeksforGeeks
-
Java Read Files - W3Schools
-
Reading A Plain Text File In Java - Stack Overflow
-
Java Read Text File - DigitalOcean
-
How To Read A File In Java - Baeldung
-
Java: Read Text File Easily - YouTube
-
Different Ways Of Reading A Text File In Java
-
Reading A Text File In Java - Tutorialspoint
-
Read From Text File In Java - SyntaxDB - Java Syntax Reference
-
How To Read A Text File In Java - Home And Learn Courses
-
How To Read A Text File In Java - Coding Game
-
Reading A Text File In Java - Quick Programming Tips
-
How To Read And Write Text File In Java
-
How To Read A File In Java
Unknown