简体   繁体   中英

My text reader program doesn't print anything

I made a really simple text reader just to test the mechanic, but it returns nothing and i am clueless! I am not very experienced in Java so it is probably a very simple and stupid mistake! here is the code:

CLASS 1

import java.io.IOException;

public class display {


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

    String path = "C:/Test.txt";
    try{
    read ro = new read(path);
    String[] fileData = ro.reader();
    for(int i = 0; i<fileData.length;i++){
        System.out.println(fileData[i]);
    }
    }catch(IOException e){
        System.out.println("The file specified could not be found!");
    }
        System.exit(0);
}

}

CLASS 2

import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class read {

private String path;

public read(String file_path){
    path = file_path;
}

public String[] reader() throws IOException{
    FileReader fR = new FileReader(path);
    BufferedReader bR = new BufferedReader(fR);

    int nOL = nOLReader();
    String[] textData = new String[nOL];
    for(int i = 0; i < nOL; i++){
        textData[i] = bR.readLine();
    }
    bR.close();
    return textData;

}

int nOLReader()throws IOException{
    FileReader fR = new FileReader(path);
    BufferedReader bR = new BufferedReader(fR);
    String cLine = bR.readLine();
    int nOL = 0;
    while(cLine != null){
        nOL++;
    }
    bR.close();

    return nOL;

}

}

Wow. That's really a lot of work you're doing just to read the file. Supposing yourelaly want to stick to your code I'll just point out:

In Class 2,

String cLine = bR.readLine();
int nOL = 0;
while(cLine != null) {
    nOL++;
}

would run into an infinite loop because you're never reading another line, just the first time is all. So make it something like:

String cLine = bR.readLine();
int nOL = 0;
while(cLine != null) {
    nOL++;
    cLine = bR.readLine();
}

PS Read some simple tutorials to just get the point of I/O in Java. Here's some code for your job .

You read only one line from file and then check out read value in forever loop (next lines are never read so you never get null inside cLine, so loop never ends). Change your method nOLReader to this (I added cLine = bR.readLine(); in the loop) and it will work:

int nOLReader() throws IOException {
    FileReader fR = new FileReader(path);
    BufferedReader bR = new BufferedReader(fR);
    String cLine = bR.readLine();
    int nOL = 0;
    while (cLine != null) {
        nOL++;
        cLine = bR.readLine();
    }
    bR.close();
    return nOL;

}

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