Java Reference
In-Depth Information
String line
=
null
null
;
line
=
is
.
readLine
();
is
.
close
();
return
return
line
;
}
finally
finally
{
iif
(
is
!=
null
null
)
is
.
close
();
}
}
/** Read the entire content of a Reader into a String;
* of course Readers should only be used for text files;
* please do not use this to read a JPEG file, for example.
*/
public
public static
static
String
readerToString
(
Reader is
)
throws
throws
IOException
{
StringBuilder sb
=
new
new
StringBuilder
();
char
char
[]
b
=
new
new
char
char
[
BLKSIZ
];
int
int
n
;
// Read a block. If it gets any chars, append them.
while
while
((
n
=
is
.
read
(
b
)) >
0
) {
sb
.
append
(
b
,
0
,
n
);
}
// Only construct the String object once, here.
return
return
sb
.
toString
();
}
/** Read the content of a Stream into a String */
public
public static
static
String
inputStreamToString
(
InputStream is
)
throws
throws
IOException
{
return
return
readerToString
(
new
new
InputStreamReader
(
is
));
}
public
public static
static
String
readAsString
(
String filename
)
throws
throws
IOException
{
return
return
readerToString
(
new
new
FileReader
(
filename
));
}
/** Write a String as the entire content of a File */
public
public static
static
void
void
stringToFile
(
String text
,
String fileName
)
throws
throws
IOException
{
BufferedWriter os
=
new
new
BufferedWriter
(
new
new
FileWriter
(
fileName
));
os
.
write
(
text
);
os
.
flush
();
os
.
close
();
}