Java how to read file to string

Java how to read file to string

How to read a file into string in java?

I have read a file into a String. The file contains various names, one name per line. Now the problem is that I want those names in a String array.

For that I have written the following code:

But I am not getting the desired results and the array obtained after splitting the string is of length 1. It means that the «fileString» doesn’t have «\n» character but the file has this «\n» character.

So How to get around this problem?

Java how to read file to string. Смотреть фото Java how to read file to string. Смотреть картинку Java how to read file to string. Картинка про Java how to read file to string. Фото Java how to read file to string

14 Answers 14

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

What about using Apache Commons ( Commons IO and Commons Lang )?

Java how to read file to string. Смотреть фото Java how to read file to string. Смотреть картинку Java how to read file to string. Картинка про Java how to read file to string. Фото Java how to read file to string

The problem is not with how you’re splitting the string; that bit is correct.

You have to review how you are reading the file to the string. You need something like this:

As suggested by Garrett Rowe and Stan James you can use java.util.Scanner :

This code does not have external dependencies.

WARNING: you should specify the charset encoding as the second parameter of the Scanner’s constructor. In this example I am using the platform’s default, but this is most certainly wrong.

Here is an example of how to use java.util.Scanner with correct resource and error handling:

Particularly i love this one using the java.nio.file package also described here.

You can optionally include the Charset as a second argument in the String constructor.

Java how to read file to string. Смотреть фото Java how to read file to string. Смотреть картинку Java how to read file to string. Картинка про Java how to read file to string. Фото Java how to read file to string

You could read your file into a List instead of a String and then convert to an array:

There is no built-in method in Java which can read an entire file. So you have the following options:

I’d use this code:

The code above has the following advantages:

Java Program to Read a File to String

There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file.

Given a text file, the task is to read the contents of a file present in a local directory and storing it in a string. Consider a file present on the system namely say it be ‘gfg.txt’. Let the random content in the file be as inserted below in the pretag block. Now we will be discussing out various ways to achieve the same. The content inside file ‘gfg.txt’ is as shown in the illustration block.

Illustration: Lines inside the file

Methods:

There are several ways to achieve the goal and with the advancement of the version in java, specific methods are there laid out which are discussed sequentially.

Methods:

Let us discuss each of them by implementing clean java programs in order to understand them.

The readString() method of File Class in Java is used to read contents to the specified file.

Syntax:

Parameters: File path with data type as Path

Return Value: This method returns the content of the file in String format.

Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String.

Example

Output:

BufferedReader is an object used to read text from a character-input stream. The readLine() method present in BufferReader method is used to read the file one line at a time and return the content.

Syntax:

Parameters: This method does not accept any parameter.

Return value: This method returns the string that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL.

Exceptions: This method throws IOException if an I/O error occurs.

Example

Output:

File.readAllBytes() method is used to read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all bytes, we pass those bytes to the string class constructor to create a string.

Syntax:

Parameter: Path which is the specified file to open for reading.

Approach:

Exceptions:

Reading from a text file and storing in a String [duplicate]

How can we read data from a text file and store in a String variable?

is it possible to pass the filename in a method and it would return the String which is the text from the file.

What kind of utilities do I have to import? A list of statements will be great.

Java how to read file to string. Смотреть фото Java how to read file to string. Смотреть картинку Java how to read file to string. Картинка про Java how to read file to string. Фото Java how to read file to string

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

These are the necersary imports:

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile(«yourFile.txt»);

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It’s just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it’s possible. It’s also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won’t. You don’t want to do it this way.

Read file into string

On this page

Related

Often you might want to read a file into a String for further processing with guava splitter, count the number of words in a file or split a string by a delimiter. This example will demonstrate how to read the content of a file into a String in java using BufferedReader, Scanner, NIO, java 8 streams, guava and apache commons. In the set up we create a constant that represents a path to the file. Using the class loader we will get the resource’s URI to use through each snippet. A word of caution, if you are reading in a very large file you will need to worry about memory consumption you may look for alternatives.

Setup

File contents

This is the content of the file-to-string.txt file.

Straight up Java

BufferedReader

Using a BufferedReader we will read entire text file into a string.

Scanner

This snippet will show how to read file contents into a string using Scanner object.

Java 7 File I/O

Read All Lines

This code will read a text file into a String using java 7 Files.readAllLines. First creating a Path to the file we will pass the Path and charset to Files.readAllLines which will read all lines of a file into arraylist. Next you could join the strings or just get the first line as shown below.

Read All Bytes

This snippet will convert a text file to a string by passing all the bytes of the file to the String constructor. Using java 7 Files utility we will use readAllBytes method that will read all the bytes.

Java 8

This snippet will read a text file into a string in java 8. We will create a Path from a URI and then call Files.lines which will use a stream to iterate over each line of the file. Next we will convert the stream to a string by calling Collectors.joining() which will join all the strings together.

Google Guava

Passing in the file and the character set this snippet will read all characters from a file into a String using guava.

Apache Commons

This snippet will read the contents of a file into a String using apache commons FileUtils.readFileToString.

Read file into string posted by Justin Musgrove on 08 July 2014

How to read a text file from «assets» directory as a string?

I have a file in my assets folder. how do I read it?

But it cast a null pointer exception.

the file is called «origin» and it is in folder assets

I tried to cast it with:

but both failed. any advice?

Java how to read file to string. Смотреть фото Java how to read file to string. Смотреть картинку Java how to read file to string. Картинка про Java how to read file to string. Фото Java how to read file to string

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

BufferedReader’s readLine() method returns a null when the end of the file is reached, so you’ll need to watch for it and avoid trying to append it to your string.

The following code should be easy enough:

Simple and to-the-point.

Short answer, do this:

It’s very straight forward, very fast, and works well for unreasonable large textfiles (100+ MB)

Long answer:

(Code at the end)

I’ve tested six methods (from slow to fast):

Conclusion:

Preallocating the buffer entirely is the fastest on very large files, but the method isn’t very versatile because the total filesize must be known ahead of time. Thats why i suggest using strBuilder with char[] buffers, its still simple and if needed easily changable to accept any input stream instead of just files. Yet its certainly fast enough for all reasonable cases.

Test Results + Code

Ps. You might have noticed that StringBuffer is slightly faster than StringBuilder. This is a bit nonsense because the classes are the same, except StringBuilder is not synchronized. If anyone can (or) can’t reproduce this. I’m most curious 🙂

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *