0

Simply - is there an easy way of determine the length of the character-stream that is coming from a textfile?

The program opens a certain text-file and then reads the characters from an object that extends FilterReader. The callback function that reads characters is the following

class: MyFilterReader

@Override
public int read(char cbuf[], int off, int len) throws IOException {

    int i = in.read(cbuf, off, len);

    return i;
}

And the other class that uses this object

class: Gui

InputStreamReader iSR = new InputStreamReader(System.in);
FileReader fr = new FileReader(file);
MyFilterReader mFR = new MyFilterReader(fr);
BufferedReader input = new BufferedReader(mFR);

char[] ch = new char[15000];
input.read(ch);
input.close();

for (int i = 0; i < ch.length; i++) {
    if (ch[i] != 0) { 
        System.out.print(ch[i]);
    }
}

In summary: I have no problems to read the characterstream, but I dont know how I in advance can determine its length so I can allocate that space to ch-vector (ch). As you see here I have temporarily set the size to an ad-hoc value of 15000:

jww
  • 97,681
  • 90
  • 411
  • 885
java
  • 1,165
  • 1
  • 25
  • 50
  • 1
    If it's from a file, can't you just look at the length of the file? – satnam Apr 14 '15 at 18:51
  • 1
    Java streams are not aware of their length. If its a file, you can read it first to get the length, then display it. I would probably go with an ArrayList or LinkedList to get around this issue. – yxre Apr 14 '15 at 18:52
  • Why? You don't need the entire file in memory to print it, or for any other other purpose I am aware of. NB @LeBarton *No* stream is aware of its length, because it isn't a well-define concept. Consider a socket that is never closed for example. – user207421 Apr 14 '15 at 19:22

0 Answers0