1

Possible Duplicate:
How to create a Java String from the contents of a file

Hi I would like to read a text file and make the message a string.

String message = StringUtils.decode(FileUtils.readFileContent(templateResource.getFile(), templateResource.getCharset(), (int) templateResource.getLength()), notification.getParams());

i'm not very good with java, how can i convert this so it would work? the patch of the file i'm trying to read is: sms-notification/info-response.1.txt

I don't want to use the decode feature perhaps as the contents of the text file are just static.

would i do something like:

String message = StringUtils.decode(FileUtils.readFileContent("sms-notification/info-response.1.txt".getFile(), templateResource.getCharset(), (int) templateResource.getLength()), notification.getParams()); ?

because that is not working.

Community
  • 1
  • 1
OakvilleWork
  • 2,377
  • 5
  • 25
  • 37
  • 2
    Same as [How to create a Java String from the contents of a file ](http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file). – Matthew Flaschen Nov 19 '10 at 15:22

1 Answers1

1

Files are a stream of bytes, Strings are a stream of chars. You need to define a charset for the conversion. If you don't explicitly set this then default OS charset will be used and you might get unexpected results.

StringBuilder sb = new StringBuilder();
try {
    BufferedReader in = new BufferedReader(new InputStreamReader(
        new FileInputStream(fileName), "UTF-8"));
    char[] buf = new char[1024];
    while ((int len  = in.read(buf, 0, buf.length)) > 0) {
        sb.append(buf, 0, len);
    }
    in.close();
} catch (IOException e) {
}
sb.toString();
Peter Knego
  • 79,991
  • 11
  • 123
  • 154