在java中读取文本文件并使其成为字符串

时间:2010-11-19 15:18:21

标签: java string netbeans text sms

  

可能重复:
  How to create a Java String from the contents of a file

您好我想阅读一个文本文件并将邮件设为字符串。

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

我对java不太好,我怎么能转换它以便它可以工作? 我正在尝试阅读的文件的补丁是:sms-notification / info-response.1.txt

我不想使用解码功能,因为文本文件的内容只是静态的。

我会做类似的事情吗?

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

因为那不起作用。

1 个答案:

答案 0 :(得分:1)

文件是字节流,字符串是字符流。您需要为转换定义字符集。如果您没有明确设置它,那么将使用默认的OS字符集,您可能会得到意外的结果。

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