简体   繁体   中英

How to read text from an inputstream, formatted as XML, with a BufferedReader.readLine() method?

I have an xml file which I included as a resource in my netbeans project.

Now, I try to read it line by line with an inputstream reader:

static InputStream nudeMap = Main.class.getResourceAsStream("overlay_map_2007.txt");

static BufferedReader br = new BufferedReader(new InputStreamReader(nudeMap,"UTF-8"));

=> this get met the error:

Exception in thread "Thread-4" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:80)

I checked the encoding of the file and it is indeed UTF-8, so I don't think it is an encoding problem. I have no experience here, but I suspect it might come from the fact that the file is actually xml formatted. First lines are:

<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns:viz="http:///www.gexf.net/1.1draft/viz" version="1.1" xmlns="http://www.gexf.net/1.1draft">

My point is, I don't want to write a parser for the use I have of the file. Do you have any clue about how I could read it as a plain old text file, without errors? Thx!

[EDIT]: to make clear: I want to read this file with br.readLine(); not with a Java Parser!

It looks to me like that your textfile isn't being found. In other words, I would guess that getResourceAsStream is returning null , and this null value is causing the NullPointerException you're getting.

Where is the overlay_map_2007.txt file within your project?

If this file isn't in the 'default' package, then you need to need to 'qualify' the name of the resource. For example, if it lies within a folder com.example.myproject , the resource name would be com/example/myproject/overlay_map_2007.txt .

I don't think you'll even have to go that far. A simple Google search yielded this fine example with its DOM Parser:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

Have a thing against DOM, then there's SAX:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM