I have a couple of issues with some of the solutions offered so far. None of the file operations use anything other than the system default character encoding. As every good developer knows, there's no such thing as plain text.
Here is how to get the platform encoding to see what you're using:
public static String getDefaultFileEncoding() {
final String keyEncoding = "file.encoding";
final String encoding = System
.getProperty(keyEncoding);
if (encoding == null) {
throw new IllegalStateException(
keyEncoding
+ "=null");
}
return encoding;
}
Alternatively, use the Charset class for a strongly typed value (alas, not every API in Java 6 has been updated to support Charset, so sometimes you need to fall back on a String). List of supported encodings.
The Reader/Writer implementations handle the character conversion. For example:
//<?xml version="1.0" encoding="UTF-8"?>
InputStream in = new FileInputStream("myfile.xml");
/*Reader reader = new InputStreamReader(in); ///WRONG!!!!!!*/
Reader reader = new InputStreamReader(in, "UTF-8"); //RIGHT
File streams are being handled in a way that may lead to resource leaks. Streams should be closed in a finally block. This ensures that they are closed even if there is an I/O error. Note that the stream initialization is before the try block.
OutputStream out = new FileOutputStream("file.txt");
try {
//write to stream
} finally {
out.close();
}
Here is an example of how to read a file into a String:
/** Copies characters from reader to writer */
public static void copy(Reader reader, Writer writer)
throws IOException {
final int bufferSize = 1024; // arbitrary value
char[] buffer = new char[bufferSize];
while (true) {
int r = reader.read(buffer);
if (r <= 0) {
break;
}
writer.write(buffer, 0, r);
}
}
/** Copies contents of File to String. Decodes from given encoding. */
public static String readToString(File file,
Charset encoding) throws IOException {
Writer writer = new StringWriter();
InputStream in = new FileInputStream(file);
Closeable resource = in;
try {
Reader reader = new InputStreamReader(in, encoding);
resource = reader;
copy(reader, writer);
} finally {
resource.close();
}
return writer.toString();
}
Sample usage:
public static void main(String[] args) {
File file = new File("foo.xml");
Charset utf8 = Charset.forName("UTF8");
try {
String s = readToString(file, utf8);
System.out.println(s);
} catch (IOException e) {
System.out
.println("Error:" + e.getLocalizedMessage());
}
}