Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

 The code below is to write a simple text file reader by creating a function that takes in the file’s path and to convert each line of text into a char array. 

function readTextFile() { var rawFile = new XMLHttpRequest(); rawFile.open("GET", "testing.txt", true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4) { var allText = rawFile.responseText; document.getElementById("textSection").innerHTML = allText; } } rawFile.send(); }

I’m getting the error  XMLHttpRequest exception 101.

It works on Firefox, but it fails to run on Google chrome and gives me the exception 101. Can anyone tell me how can I get this work on other browsers as well (Especially Chrome)? 

1 Answer

0 votes
by (19.7k points)

You have to look for the status 0 (loading files locally with XMLHttpRequest, the status is not returned because it’s not from a web server)

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;

                alert(allText);

            }

        }

    }

    rawFile.send(null);

}

Do specify file:// in your filename:

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

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...