Is any IO format reader in Java?

R

RC

in java.io.*;

In PrintWriter and PrintStream classes
they both have two format(...) methods.
So I can write similar like C/C++

printf, fprintf and sprintf in format like %5.1f.

But I can't find an IO class has format reader
similar to C/C++

scanf, fscanf and sscanf

I have some input data look like

" 0.1-10.2" (two spaces at the front).
They are two float numbers 0.1 and -10.2 (NOT 0.1 minus 10.2)!

The best way to read this is read them in format "%5.1f%5.1f"

If the data look like " 0.1 -10.2", then I can use StringTokenizer
Now I have to read 5 characters a time!
 
A

a24900

in java.io.*;

In PrintWriter and PrintStream classes
they both have two format(...) methods.
So I can write similar like C/C++

printf, fprintf and sprintf in format like %5.1f.

But I can't find an IO class has format reader
similar to C/C++

scanf, fscanf and sscanf

I have some input data look like

" 0.1-10.2" (two spaces at the front).
They are two float numbers 0.1 and -10.2 (NOT 0.1 minus 10.2)!

The best way to read this is read them in format "%5.1f%5.1f"

Fixed field-width with no separating whitespace? That's ugly to do in
Java. At least one guaranteed whitespace or any other separator in
between and you could use Scanner. But without a separator you either
need to look for a third-party library, try to make sense out of
DecimalFormat.parse() and accompanying pattern junk, or do some good
old coding, like it follows.

int fieldWidths[] = { 5, 5 };
BuffredReader in = ...

....

String line;
while((line = in.readLine()) != null) {
int start = 0;
for(int width: fieldWiths) {
int end = start + width;
String field = line.substring(start, end);
if(field.length() != width) {
// ups, input to short
}
double value = Double.parseDouble(field);
// do something with the value

start = end;
}
}
 
L

Lew

Fixed field-width with no separating whitespace? That's ugly to do in
Java. At least one guaranteed whitespace or any other separator in

Shouldn't be too bad with java.nio Buffers.
 

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,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top