Нужна помощь с программой, возникли проблемы с FileInputStream только чтение одной строки текстового файла.[HomeworkHelp] - PullRequest
1 голос
/ 01 марта 2012

Итак, мне нужно создать программу, которая в основном проверяет правильность вложенности текстового документа XML.Я подумал, что это на самом деле одно из наших простых заданий в этом семестре, но у меня проблемы с чтением текстового файла построчно.Я реализовал код для FileInputStream, который нам предоставил наш профессор, и оттуда у меня возникли проблемы с ним.По сути, мой код проверяет первую строку текстового файла, а затем заканчивается.Я должен делать что-то не так с моим FileInputStream, я просто не совсем уверен, что.Любая помощь приветствуется.

// The XMLParser class prompts the user for a filename and reads an XML 
// document from the given text file. The program then reports that either the 
// document is valid based on XML rules or there was an error at a certain 
// line of input due to a violation of rules of XML tags.

import java.io.*;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;

public class XMLParser {        
public static void main(String[] args) throws IOException{

    //creates a scanner to read the users input of the file name
    Scanner input = new Scanner(System.in);

    //creates an integer that will be incremented for every line read
    //to help with error reporting
    int currentLine = 1;

    //creates a stack that elements will be pushed on to
    //and popped off of, strings to represent opening and closing
    //tags of an xml document, and a string to represent the root 
    //tag (the first tag used)
    Stack<String> stack = new Stack<String>();
    String open = "<";
    String close = "</";
    String root = "";


    //prompts the user to input a file name then reads from
    // the file the user entered
    System.out.println("Enter the name of the file to be read: ");
    String fileName = input.next();
    FileInputStream fis = new FileInputStream(fileName);
    InputStreamReader inStream = new InputStreamReader(fis);
    BufferedReader stdin = new BufferedReader(inStream);
    String data = stdin.readLine();

    String nextDataValue;
    StringTokenizer tokenizer = new StringTokenizer(data);

    while (tokenizer.hasMoreTokens()) {
        nextDataValue = tokenizer.nextToken().trim();

        //if the xml document begins with anything other than
        //a root tag, an error is reported and the program ends
        if (root.equals("") && !nextDataValue.startsWith(open)) {
            System.out.println("PARSE ERROR Line 1, your XML document does not start with an opening tag and is therefore invalid\nProgram terminating normally...");
            break;
        }

        //pushes an "opening tag" onto the stack
        else if (nextDataValue.startsWith(open) && !nextDataValue.startsWith(close)) {
            stack.push(nextDataValue);

            //checks if there is already a root value, and if there
            //is not it adds one
            if (root.equals("")) {
                root = root + nextDataValue;
            }

        }

        //if a closing tag is found, this pops the stack and compares
        //the closing tag with an opening tag to see if it is properly
        //nested, if not an error statement is printed and the program
        //ends
        if (nextDataValue.startsWith(close)) {
            String compareClose = nextDataValue;
            String compareOpen = stack.pop();
            compareClose = compareClose.replace("/", "");
            if (!compareClose.equals(compareOpen)) {
                System.out.println("PARSE ERROR Line " + currentLine + ", you have improperly nested the tag: " + compareOpen);
                break;
            }
            //if the closing tag is the root tag and there is nothing
            //after this closing tag, the document is valid.
            if (compareOpen.equals(root) && !tokenizer.hasMoreTokens()) {
                System.out.println("Input XML document is valid");
            }
        }       


        currentLine++;
    }




}
}

tl; dr: Почему мой FileInputStream проходит одну строку кода, а затем просто останавливается.Я сделал что-то не так в своем цикле while или это что-то еще, что я не знаю?

Любая помощь очень ценится, спасибо!

Ответы [ 4 ]

4 голосов
/ 01 марта 2012

Ваша проблема лежит в этой строке: String data = stdin.readLine();.То, как вы это делаете, заставит программу прочитать только одну строку, проверить ее и выйти.Вам нужно выполнить цикл while, подобный следующему:

String data = "";
while ( (data = stdin.readLine()) != null)
{
    //Read and validate the line you are reading
}

Это позволит вам загружать новую строку текста за итерацию.Как только EOF будет обнаружен, stdin.readLine() должен вернуть ноль, тем самым нарушая ваш цикл и останавливая выполнение вашей программы.

1 голос
/ 01 марта 2012

Как они сказали, вы читаете только одну строку из BufferedReader

И вам также нужно заметить пустой элемент, такой как

<emptyElement />

String open = "<";
String close = "</";
String close1 = "/>"
0 голосов
/ 01 марта 2012

Вы должны повторно вызывать readLine, например, в цикле, чтобы прочитать более одной строки.

0 голосов
/ 01 марта 2012

Вы читаете строку только один раз. До цикла.

...