Rectangle 27 138

You can use this:

try {
        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.help);

        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        txtHelp.setText(new String(b));
    } catch (Exception e) {
        // e.printStackTrace();
        txtHelp.setText("Error: can't show help.");
    }

I am not sure the Inputstream.available() is the correct choice here, rather read n to a ByteArrayOutputStream untill n == -1.

This may not work for large resources. It depends on the size of the inputstream read buffer and could only return a part of the resource.

@d4n3 is right, the documentation of the input stream available method states: "Returns an estimated number of bytes that can be read or skipped without blocking for more input. Note that this method provides such a weak guarantee that it is not very useful in practice"

Look at the android docs for InputStream.available. If I get it right they say that it should not be used for this purpose. Who'd thought that it be that hard to read the content of a stupid file...

And you should not catch general Exception. Catch IOException instead.

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 53

What if you use a character-based BufferedReader instead of byte-based InputStream?

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) { ... }

Don't forget that readLine() skips the new-lines!

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 3

// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(id);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    byte[] readBuffer = new byte[4 * 1024];

    try {
        int read;
        do {
            read = is.read(readBuffer, 0, readBuffer.length);
            if(read == -1) {
                break;
            }
            bout.write(readBuffer, 0, read);
        } while(true);

        return bout.toByteArray();
    }finally {
        is.close();
    }
}

    // reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
    return new String(getResource(id, getContext()), encoding);
}

    // reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
    return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}

or from a test case, add

public byte[] getResource(int id) throws IOException {
        return getResource(id, getContext());
}

And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.

openRawResource()

I dont know, but that certainly is standard. Updating examples.

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 24

If you use IOUtils from apache "commons-io" it's even easier:

InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
'commons-io:commons-io:2.4'

But generally, importing external 3rd party libs to avoid writing 3 more lines of code.. seem like an overkill.

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 2

This is another method which will definitely work, but I cant get it to read multiple text files to view in multiple textviews in a single activity, anyone can help?

TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
    helloTxt.setText(readTxt());
}

private String readTxt(){

 InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
try {
i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
  }
  inputStream.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}

 return byteArrayOutputStream.toString();
}

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 1

1.First create a Directory folder and name it raw inside the res folder 2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt.... 3.copy and paste the text you want inside the .txt file you created"articles.txt" 4.dont forget to include a textview in your main.xml MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gettingtoknowthe_os);

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
    helloTxt.setText(readTxt());

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();//to exclude the ActionBar
}

private String readTxt() {

    //getting the .txt file
    InputStream inputStream = getResources().openRawResource(R.raw.articles);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        int i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArrayOutputStream.toString();
}

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 1

@borislemke you can do this by similar way like

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

Android read text raw resource file - Stack Overflow

android text resources
Rectangle 27 1122

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

In Java 8, BufferedReader added a new method, lines() to produce a Stream<String>. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

try (BufferedReader r = Files.newBufferedReader(path, encoding)) {
  r.lines().forEach(System.out::println);
}

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream<String> is one way to do this, if your input "records" happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Technically speaking, it's O(n) in time and space. Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes. Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file. Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by "decode", the memory requirement is much less. Time-wise, I don't think you'll find anything faster in the core Java libs.

Possible typo? NIO has a Charset (not CharSet) class called java.nio.charset.Charset. Is this what CharSet should have been?

Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine. May it be in relation with this issue : bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ? I finally went with the proposition of Jon Skeet which doesn't suffer from this bug. Anyways, I just wanted to give the info, for other people, just in case...

@Sbastien Nussbaumer: I also bumped on this problem. Amazing that the bug has been marked "Will Not Fix". This essentially means that FileChannel#map is, in general, unusable.

@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: "This bug is not available." Google cached the site at webcache.googleusercontent.com/search?q=cache:bugs.sun.com/

How do I create a Java string from the contents of a file? - Stack Ove...

java file file-io io
Rectangle 27 1121

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

In Java 8, BufferedReader added a new method, lines() to produce a Stream<String>. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

try (BufferedReader r = Files.newBufferedReader(path, encoding)) {
  r.lines().forEach(System.out::println);
}

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream<String> is one way to do this, if your input "records" happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Technically speaking, it's O(n) in time and space. Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes. Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file. Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by "decode", the memory requirement is much less. Time-wise, I don't think you'll find anything faster in the core Java libs.

Possible typo? NIO has a Charset (not CharSet) class called java.nio.charset.Charset. Is this what CharSet should have been?

Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine. May it be in relation with this issue : bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ? I finally went with the proposition of Jon Skeet which doesn't suffer from this bug. Anyways, I just wanted to give the info, for other people, just in case...

@Sbastien Nussbaumer: I also bumped on this problem. Amazing that the bug has been marked "Will Not Fix". This essentially means that FileChannel#map is, in general, unusable.

@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: "This bug is not available." Google cached the site at webcache.googleusercontent.com/search?q=cache:bugs.sun.com/

How do I create a Java string from the contents of a file? - Stack Ove...

java file file-io io
Rectangle 27 1116

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM.

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Technically speaking, it's O(n) in time and space. Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes. Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file. Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by "decode", the memory requirement is much less. Time-wise, I don't think you'll find anything faster in the core Java libs.

Possible typo? NIO has a Charset (not CharSet) class called java.nio.charset.Charset. Is this what CharSet should have been?

Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine. May it be in relation with this issue : bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ? I finally went with the proposition of Jon Skeet which doesn't suffer from this bug. Anyways, I just wanted to give the info, for other people, just in case...

@Sbastien Nussbaumer: I also bumped on this problem. Amazing that the bug has been marked "Will Not Fix". This essentially means that FileChannel#map is, in general, unusable.

@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: "This bug is not available." Google cached the site at webcache.googleusercontent.com/search?q=cache:bugs.sun.com/

How do I create a Java string from the contents of a file? - Stack Ove...

java file file-io io
Rectangle 27 1116

Read all text from a file

Here's a compact, robust idiom for Java 7, wrapped up in a utility method:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM.

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

The StandardCharsets class define some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Technically speaking, it's O(n) in time and space. Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes. Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file. Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by "decode", the memory requirement is much less. Time-wise, I don't think you'll find anything faster in the core Java libs.

Possible typo? NIO has a Charset (not CharSet) class called java.nio.charset.Charset. Is this what CharSet should have been?

Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine. May it be in relation with this issue : bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ? I finally went with the proposition of Jon Skeet which doesn't suffer from this bug. Anyways, I just wanted to give the info, for other people, just in case...

@Sbastien Nussbaumer: I also bumped on this problem. Amazing that the bug has been marked "Will Not Fix". This essentially means that FileChannel#map is, in general, unusable.

@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: "This bug is not available." Google cached the site at webcache.googleusercontent.com/search?q=cache:bugs.sun.com/

How do I create a Java string from the contents of a file? - Stack Ove...

java file file-io io
Rectangle 27 94

Say you read a Text File.

This will work for general reading a String from Text. If you would like to read longer text (large size of text), then use the method that other people here were mentioned such as buffered (reserve the size of the text in memory space).

NSString* filePath = @""//file path...
NSString* fileRoot = [[NSBundle mainBundle] 
               pathForResource:filePath ofType:@"txt"];
// read everything from text
NSString* fileContents = 
      [NSString stringWithContentsOfFile:fileRoot 
       encoding:NSUTF8StringEncoding error:nil];

// first, separate by new line
NSArray* allLinedStrings = 
      [fileContents componentsSeparatedByCharactersInSet:
      [NSCharacterSet newlineCharacterSet]];

// then break down even further 
NSString* strsInOneLine = 
      [allLinedStrings objectAtIndex:0];

// choose whatever input identity you have decided. in this case ;
NSArray* singleStrs = 
      [currentPointString componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@";"]];

There you have it.

i have a 70 mb file , using this code to read file doesn't hep me it increases memory linearly. can any one help me?

This is no response to the question. The question was to read a file line by line to reduce memory usage

Objective-C: Reading a file line by line - Stack Overflow

objective-c file-io nsstring enumerate nsstream
Rectangle 27 94

Say you read a Text File.

This will work for general reading a String from Text. If you would like to read longer text (large size of text), then use the method that other people here were mentioned such as buffered (reserve the size of the text in memory space).

NSString* filePath = @""//file path...
NSString* fileRoot = [[NSBundle mainBundle] 
               pathForResource:filePath ofType:@"txt"];
// read everything from text
NSString* fileContents = 
      [NSString stringWithContentsOfFile:fileRoot 
       encoding:NSUTF8StringEncoding error:nil];

// first, separate by new line
NSArray* allLinedStrings = 
      [fileContents componentsSeparatedByCharactersInSet:
      [NSCharacterSet newlineCharacterSet]];

// then break down even further 
NSString* strsInOneLine = 
      [allLinedStrings objectAtIndex:0];

// choose whatever input identity you have decided. in this case ;
NSArray* singleStrs = 
      [currentPointString componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@";"]];

There you have it.

i have a 70 mb file , using this code to read file doesn't hep me it increases memory linearly. can any one help me?

This is no response to the question. The question was to read a file line by line to reduce memory usage

Objective-C: Reading a file line by line - Stack Overflow

objective-c file-io nsstring enumerate nsstream
Rectangle 27 53

Guava has a "toString" method for reading a file into a String:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

This method does not require the file to be in the classpath (as in Jon Skeet previous answer).

String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));

Utils to read resource text file to String (Java) - Stack Overflow

java string text resources
Rectangle 27 52

Guava has a "toString" method for reading a file into a String:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

This method does not require the file to be in the classpath (as in Jon Skeet previous answer).

String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));

Utils to read resource text file to String (Java) - Stack Overflow

java string text resources
Rectangle 27 52

Guava has a "toString" method for reading a file into a String:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

This method does not require the file to be in the classpath (as in Jon Skeet previous answer).

String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));

Utils to read resource text file to String (Java) - Stack Overflow

java string text resources
Rectangle 27 171

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text.toString());

following links can also help you :

your link would be helps me to achieve

while ((line = br.readLine()) != null) {     if(line.length() > 0) {       //do your stuff     }            }

close() should be done on a finally block.

@Shruti how to add the file into SD card

java - How can I read a text file in Android? - Stack Overflow

java android exception-handling inputstream
Rectangle 27 27

You can use a FileReader object to read text file here is example code:

<div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

Is it possible to skip the "Select a file" option and instead define the file to be read in my code? This is actually what I need. Not the user should choose the file but I should.

Worked! Thanks a lot!

there`s a way to solve encoding?

Read a local text file using Javascript - Stack Overflow

javascript text-files
Rectangle 27 27

You can use a FileReader object to read text file here is example code:

<div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

Is it possible to skip the "Select a file" option and instead define the file to be read in my code? This is actually what I need. Not the user should choose the file but I should.

Worked! Thanks a lot!

there`s a way to solve encoding?

Read a local text file using Javascript - Stack Overflow

javascript text-files
Rectangle 27 6

Pure and simple Java 8 solution

/**
 * Reads given resource file as a string.
 *
 * @param resourceFileName the path to the resource file
 * @return the file's contents
 */
public String getResourceFileAsString(String resourceFileName) {
    InputStream is = getClass().getClassLoader().getResourceAsStream(resourceFileName);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    return reader.lines().collect(Collectors.joining("\n"));
}

And it also works with resources in jar files.

There's no need for big, fat libraries. Unless you are already using Guava or Apache Commons IO, adding those libraries to your project just to be able to read a file as a string seems a bit too much.

no need for libraries, yeah, let's reinvent the wheel every time.

@zakmck please try to keep your comments constructive. As you grow up as a mature developer, you learn that sometimes you do want to "reinvent the wheel". For instance, you may need to keep your binary below something threshold size. Libraries often make your application size grow by orders of magnitude. One could argue just the opposite of what you said: "No need to write code. Yeah, let's just import libraries every time". Would you really prefer importing a library just to save you 3 lines of code? I bet that adding the library will increase your LOC by more than that. The key is balance.

Btw, I just saw you posted an answer here as well saying that you wrote some methods in your own library depending on Guava but you "like JDK-only methods suggested in other answers and [you] think [you]'ll change these that way". Good to know, glad that I could help :-)

[Would you really prefer importing a library just to save you 3 lines of code] ==> Given that I'm running stuff on cloud servers, each having a minimum of 16GB RAM, of course I do it. I would use C (or Assembler) if I had C=64 hardware requirements. In nowadays world having readable, factorised, less error-prone code is usually way more important than saving a few KBs.

Well, not every one is running stuff on the cloud. There are embedded systems everywhere running Java, for example. I just don't see your point in criticizing answers that provide totally valid approaches, given that you mention yourself that you're going to accept the suggestion to use JDK directly in your own code. Anyway, let's please try to keep comments strictly to help improve answers, not to discuss opinions.

Utils to read resource text file to String (Java) - Stack Overflow

java string text resources