【问题标题】:reading a text file in java and making it a string [duplicate]在java中读取文本文件并将其设为字符串[重复]
【发布时间】:2011-05-12 16:47:24
【问题描述】:

可能重复:
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()); ?

因为那行不通。

【问题讨论】:

标签: java string netbeans text sms


【解决方案1】:

文件是字节流,字符串是字符流。您需要为转换定义一个字符集。如果您没有明确设置,则将使用默认操作系统字符集,您可能会得到意想不到的结果。

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

【讨论】:

  • 嗯,你是对的。帖子已更正。
猜你喜欢
  • 1970-01-01
  • 2014-09-25
  • 2016-07-14
  • 2013-04-08
  • 2012-10-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
相关资源
最近更新 更多