【问题标题】:How to convert file content to a string? [duplicate]如何将文件内容转换为字符串? [复制]
【发布时间】:2016-04-24 22:06:31
【问题描述】:

我的构造函数是这样的:

MyClassName(File f) throws Exception;

一个txt文件看起来像这样:

. . . . .
. . . . .
. x . . .
. x x . .
. . . . .
. . . . .

打开文件时,如何将其转换为字符串?

像这样:

". . . . .\n
. . . . .\n
. x . . .\n
. x x . .\n
. . . . .\n
. . . . .\n"

【问题讨论】:

  • 不清楚你的意思 - 听起来你想创建一个字符串文字,但你不能拥有多行字符串文字(无论如何,除非明确连接这些行)。
  • new String(Files.readAllBytes(f.toPath()))
  • @ElliottFrisch 值得一提的是这里的文件编码 - 平台默认值可能不正确。尽管考虑到内容,它应该不会产生太大影响。

标签: java arrays string file 2d


【解决方案1】:

这个方法读取一个文件:

 public String readFile(File file) {
    StringBuffer stringBuffer = new StringBuffer();
    if (file.exists())
        try {
            //read data from file
            FileInputStream fileInputStream = new FileInputStream(file);
            int c;
            while ((c = fileInputStream.read()) != -1){
                stringBuffer.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    return stringBuffer.toString();
}

以及来自构造函数的调用

public MyClassName(File f) throws Exception{
     String text = readFile(f);
}

【讨论】:

  • 愚蠢的问题 - 这比 new String(Files.readAllBytes(f.toPath())) 好多少?它肯定更多更长......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2014-08-05
  • 2018-09-25
  • 2014-12-05
  • 2014-06-11
  • 2018-11-04
相关资源
最近更新 更多