用java逐行读取

用java逐行读取,java,xml,servlets,request,byte,Java,Xml,Servlets,Request,Byte,我从一个帖子收到一个xml文件。 我试图读取xml文件中的内容,但得到的答案对我来说不符合逻辑。 我只想读第三行,但这似乎是我的程序唯一不想读的一行 .JAVA: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int line=0; byte[] buffer=new byte[1000];

我从一个帖子收到一个xml文件。 我试图读取xml文件中的内容,但得到的答案对我来说不符合逻辑。 我只想读第三行,但这似乎是我的程序唯一不想读的一行

.JAVA:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    int line=0;
    byte[] buffer=new byte[1000];
    while(line<5) {
        request.getInputStream().readLine(buffer, 0, buffer.length);
        line++;
    }
    String name = new String(buffer, "UTF-8");
    System.out.println(name);
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Trias xmlns:siri="http://www.siri.org.uk/siri" xmlns="http://www.vdv.de/trias" xmlns:ns3="http://www.ifopt.org.uk/acsb" xmlns:ns4="http://www.ifopt.org.uk/ifopt" xmlns:ns5="http://datex2.eu/schema/1_0/1_0" version="1.2">
    <siri:CheckStatusRequest>
        <siri:RequestTimestamp>2018-03-12T16:36:30.002+01:00</siri:RequestTimestamp>
protectedvoiddopost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
内线=0;
字节[]缓冲区=新字节[1000];

当使用
readLine()
读取时,应检查返回值以确保读取未超过流的末尾

int line = 0;
byte[] buffer = new byte[1000];
while (line < 5) {
    int read = request.getInputStream().readLine(buffer, 0, buffer.length);
    if (read < 0) {
        break; // end of stream reachead
    }
    line++;
}
int行=0;
字节[]缓冲区=新字节[1000];
while(第5行){
int read=request.getInputStream().readLine(buffer,0,buffer.length);
如果(读取<0){
break;//流的末尾reachhead
}
line++;
}

但是,最好使用解析器读取XML,例如。这样,您就可以专注于业务任务,而不必处理框架任务,例如。

当使用
readLine()
读取时,您应该检查返回值,以确保没有读到流的末尾

int line = 0;
byte[] buffer = new byte[1000];
while (line < 5) {
    int read = request.getInputStream().readLine(buffer, 0, buffer.length);
    if (read < 0) {
        break; // end of stream reachead
    }
    line++;
}
int行=0;
字节[]缓冲区=新字节[1000];
while(第5行){
int read=request.getInputStream().readLine(buffer,0,buffer.length);
如果(读取<0){
break;//流的末尾reachhead
}
line++;
}

但是,最好使用解析器读取XML,例如。这样,您可以专注于业务任务,而不必处理框架任务,例如。

您不想假设第三行包含感兴趣的内容。XML元素之间不需要换行符。例如,请求正文可以作为以下内容传递:

<Trias …><siri:CheckStatusRequest><siri:RequestTimestamp>2018-03-12T16:36:30.002+01:00</siri:RequestTimestamp></siri:CheckStatusRequest></Trias>

您不希望假定第三行包含感兴趣的内容。XML元素之间不需要换行符。例如,请求正文可以按以下方式传递:

<Trias …><siri:CheckStatusRequest><siri:RequestTimestamp>2018-03-12T16:36:30.002+01:00</siri:RequestTimestamp></siri:CheckStatusRequest></Trias>

您确实不希望以行的形式读取XML—主要参考框架混淆和不必要的复杂性。请改用XML解析器。您确实不希望以行的形式读取XML—主要参考框架混淆和不必要的复杂性。请改用XML解析器。