Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

java output from a file

Posted on 2002-04-17
9
Medium Priority
?
189 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 9

Accepted Solution

by:
Venci75 earned 300 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses

610 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