开发者

reading a text file in java and making it a string [duplicate]

开发者 https://www.devze.com 2023-01-26 12:21 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How to create a Java String from the contents of a file
This question already has answers here: Closed 12 years ago.

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:

开发者_如何学GoString message = StringUtils.decode(FileUtils.readFileContent("sms-notification/info-response.1.txt".getFile(), templateResource.getCharset(), (int) templateResource.getLength()), notification.getParams()); ?

because that is not working.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消