how to read a .txt file

M

Michael Foley

private String filereader(FileInputStream is ) {

int MAX_BUF = 40000;
byte[] buf = new byte [MAX_BUF];
int total = 0, count;

try {
for (total = 0; total < MAX_BUF - 1; )
{
count = is.read (buf, total, MAX_BUF - 1 - total);
if (count < 0) break ;
total += count;
}
is.close();
return new String(buf, 0, total);
}

catch (Exception e) {
System.out.println("Error in file reader: " + e);
return "Error";
}


Regards,

Mike
 
A

Andrew Thompson

Michael Foley wrote:

Please refrain from top-posting.
private String filereader(FileInputStream is ) {
.....

Do you intend to tell the OP the other 71* ways to
read a file? I think it might help the OP more to work
through the I/O section fo the Java Tutorial.

Especially since, if using this code, the end user might
not be able to distinguish between a file with the singular
text "Error", and the result of a method that..
catch (Exception e) {
System.out.println("Error in file reader: " + e);
return "Error";
}

...returns "Error" when it encounters a problem!

* Sure, I just plucked that figure out of the air.
Anybody want to count them?

Andrew T.
 
J

John W. Kennedy

how to read a .txt file?

Depending on your needs, either:

BufferedReader reader = new BufferedReader(new FileReader(...));
for (;;) {
String line = reader.readLine();
if (line == null) break;
...
}
reader.close();

or

Scanner scanner = new Scanner(...);
while (scanner.hasNext()) {
int i = scanner.nextInt(); // or whatever
...
}
scanner.close();
 
L

Lew

Depending on your needs, either:

BufferedReader reader = new BufferedReader(new FileReader(...));
for (;;) {
String line = reader.readLine();
if (line == null) break;
...
}
reader.close();

or

Scanner scanner = new Scanner(...);
while (scanner.hasNext()) {
int i = scanner.nextInt(); // or whatever
...
}
scanner.close();

Or you could use the java.nio package and open a channel to read into a
buffer, probably a CharBuffer but needs vary.

Andrew had the best suggestion: study the I/O (and, I venture to say also the
NIO) tutorials.

Standard sources like these tutorials are likeliest to have been proofread, to
contain examples you can use, to be (relatively) free of wrong-headedness and
the arrogant presumption that the respondent is competent, and to avoid other
ills that might beset the Usenet querent.

<http://java.sun.com/docs/books/tutorial/index.html>

GIYF.

- Lew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top