1

I'm new here and just struggling with trying to get a text file read. On every line there is a word and a corresponding numeric code. The idea is to read it and put the code and word in separate variables. I don't know so much about this area, but I've been looking around online and came up with the following:

try{
    FileReader freader=new FileReader(f); 
    BufferedReader inFile=new BufferedReader(freader);
    while (inFile.readLine()!=null){
       String s=null;
       s=inFile.readLine();
       System.out.println(s);
               String[] tokens=s.split(" ");
       string=tokens[0];
       System.out.println(string);
       code=tokens[1];
       System.out.println(code);
       c.insert(string, code);
    }//end outer while
}//end try

The issue is that the first line of the text file isn't read. And then it skips a line every time! (In other words, only the 1st, 3rd, 5th, 7th lines, etc. are read)

As I said above, I'm new, and I don't know much about all the different things I saw on different sites online (like why everything is bufferedThis or bufferedThat, or how to use all the tokenizer things properly). I was trying a few different things at different times, and ended up with this.

4

2 に答える 2

7

while ループがファイルの半分の行を飲み込んでいます。

while (inFile.readLine()!=null)

それは行を読み取りますが、それを何にも割り当てません。ループの前にa を宣言し、Stringこのように各行を読み取ります。

String line;
while ((line = inFile.readLine()) != null)

これで変数lineはループ内で使用できるようになるため、ループ内で呼び出す必要はありませんinFile.readLine()

于 2012-10-14T21:22:45.187 に答える
0

あなたの問題は、すべての行を 2 回読んでいることです。1 つは while ブロック内にあり、もう 1 つは while の状態にあります。

これを試して:

try{
    FileReader freader=new FileReader(f); 
    BufferedReader inFile=new BufferedReader(freader);
    String s;
    while ((s=inFile.readLine())!=null){       
       System.out.println(s);
        String[] tokens=s.split(" ");
       string=tokens[0];
       System.out.println(string);
       code=tokens[1];
       System.out.println(code);
       c.insert(string, code);
    }//end outer while
}//end try
于 2012-10-14T21:27:07.177 に答える