Solved

java output from a file

Posted on 2002-04-17
9
170 Views
Last Modified: 2010-03-31
Hi guys,
I have a problem reading the results from a text file results.txt and outputting them to a text area in a gui,
I mean at the minute I'm using a FOR loop and a readline() method from the bufferedReader class ,results(below) is the text file  and this this is the working code :

try {

bufferedReader  = new BufferedReader(new FileReader(results));

            for(int n =0; n < 100; n++)
             
              {
                queryResult += bufferedReader.readLine();
       
              }
         }

         catch (IOException e) {}


        return queryResult;
    }
but this FOR loop gives me the first 100 lines of the text file and stops, I want to read until the end of file and then stop the ouput, queryResult takes the output from the file. I have been trying a while loop but have not got it working yet,
any help would be greatly welcomed,
thanks
Damo.
0
Comment
Question by:dpconnagh
9 Comments
 
LVL 9

Accepted Solution

by:
Venci75 earned 75 total points
ID: 6948151
try {
  bufferedReader  = new BufferedReader(new FileReader(results));
  String line
  while ((line=bufferedReader.readLine()) != null) {
    queryResult += line;
  }
} catch (IOException e) {}

return queryResult;
   
0
 
LVL 16

Expert Comment

by:Peter Kwan
ID: 6948162
You can try this:

String line;
line = bufferedReader.readLine();

while (line != null) {
   queryResult += line;
   line = bufferedReader.readLine();
}
0
 
LVL 2

Expert Comment

by:mzimmer74
ID: 6948512
Here is the one I personally use (as I don't like having an assignment in the while loop) but either of the two previous also work:

BufferedReader bufferedReader ......

while (bufferedReader.ready())
{
  queryResult += bufferedReader.readLine();
}
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 6952086
When reading _all_ contents of a file, I usually do something like this:

    private static String readFully(String filename) throws Exception {
        File file = new File(filename);
        FileReader in = new FileReader(file);
        char[] buf = new char[(int)file.length()];
        in.read(buf);
        in.close();
        return new String(buf);
    }

This has two benefits. First, it grabs the entire file at once instead of in line-oriented chunks. This is more performant than using a BufferedReader.readLine which a) reads the file in buffer-size chunks meaning that there are more physical I/O requests, b) searches through the buffered data to find line terminators and c) constructs new String objects for each line that it returns.

Second, this technique _also_ preserves line terminators in the input. Each line returned from BufferedReader.readLine has the line terminators knocked off. You're probably gonna want these for intelligible display in the JTextArea. To obtain the equivalent, you'd have to add the line terminators back on like this:

    private static String readFully(String filename) throws Exception {
        String terminator = System.getProperty("line.separator");
        File file = new File(filename);
        BufferedReader in = new BufferedReader(new FileReader(file));
        StringBuffer buf = new StringBuffer((int)file.length());
        String line = null;

        while ((line = in.readLine()) != null) {
            buf.append(line).append(terminator);
        }
        in.close();
        return buf.toString();
    }

BTW, notice that I used a StringBuffer to build the content? Don't use String concatenation as you did in your post and as the others did in their comments. String concatenation has a huge amount of overhead from construction of temporary StringBuffers and char[] resizing and copying. On even small files, say 2K, concatenating into a StringBuffer is five times faster. By the time you hit a file size of 10K, you're looking at better than 20 times faster. Reading a 50K file is over 100 times faster. And I stopped timing when I got to a 100K file and the StringBuffer method was 750 times faster -- using String concatenation it took more than 20 seconds just to read the file one time. Reading directly into a char[] as I originally suggested is about 30% faster than using the BufferedReader to read lines regardless of the file size. (All timings were taken with JDK 1.3 on NT4.)

In short, read the file all at once if you can. And don't do concatenation of non-constant Strings unless you just don't care about performance.

Best regards,
Jim Cakalic
0
 
LVL 9

Expert Comment

by:Venci75
ID: 7972313
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
Answered by: Venci75
Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
Venci75
EE Cleanup Volunteer
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 7975034
I'll give you this one, although I think you'd be hard pressed to deny that my answer was technically superior. (No slight intended.)

Jim
0
 
LVL 9

Expert Comment

by:Venci75
ID: 7975175
yes - it is probably a better solution, but dpconnagh actually changes the data while reading the file - it removes the new line character for the file content. Also - I was the first who suggested a solution. Anyway - I think you deserve points - so the best would be if the points are splitted. I didn't suggested this because of the cleanup recomendations.
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 7975446
Well, choosing not to debate the point, I only wanted to voice my opinion about the chosen answer. As I stated previously, I'm OK with the resolution.

Jim
0
 

Expert Comment

by:SpideyMod
ID: 8020400
per recommendation

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
thymeleaf natural templating vs JSP 2 100
jar file executable 12 52
Why my table column Id is not passed to java object? 4 39
Is there a simpler dropbox system? 10 22
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question