On Thu, 29 Jan 2009, McGregor wrote:
> I'm trying to read a file line by line with following code-snippet:
>
> -----------------------------**-------------------------------
> BufferedReader test = new BufferedReader(new FileReader(datei));
> String tmp = "";
> Vector data = new Vector();
> boolean first = true;
> int breaker = 0;
> int position = 0;
> while ((tmp = test.readLine()) != null) {
> if (!first) data.addElement(tmp); else first = false;
> if (tmp.contains("%%EOF")) breaker = position;
> position++;
> }
> while (data.size() > breaker) data.remove(data.size()-1);
> -----------------------------**-------------------------------
>
> there are many "%%EOF" - lines within this file. I need to get the
> last one and this is my solution to get the whole data from the second
> line to the last line with "%%EOF"
>
> But I encountered some problems. Some lines are very long, i.e. more
> than 8000 characters (varied, depends on the file). When reading the
> file using the above code I only get aprox. 1520 characters and the
> remaing characters are lost and reading stops with no error at all.
Odd. Could you try running this test program:
http://urchin.earth.li/~twic/tmp/LongLines.java
?
If there are any problems with reading lines up to 8000 characters long,
it should fail with an IOException. On my machine (java 1.5.0_16), it
completes successfully.
The thing is, your code looks like it should work to me. It's not quite
how i would have written it, but it ought to work.
> So I need some other solution to read my file. Keep in mind, that I
> need to compare strings...
Here's how i'd do it:
public static List<String> readToLastMarker(BufferedReader in, String marker) throws IOException {
List<String> acceptedLines = new ArrayList<String>();
List<String> candidateLines = new ArrayList<String>();
String firstLine = in.readLine(); // ignore the first line
String line;
while ((line = in.readLine()) != null) {
if (line.contains(marker)) {
acceptedLines.addAll(candidateLines);
candidateLines.clear();
candidateLines.add(line); // do you really want to do this?
}
else {
candidateLines.add(line);
}
}
return acceptedLines;
}
tom
--
I am the best at what i do.