如何将文件内容转换为字符串?
问题描述:
我有一个构造函数如下:如何将文件内容转换为字符串?
MyClassName(File f) throws Exception;
和TXT文件看起来是这样的:
. . . . .
. . . . .
. x . . .
. x x . .
. . . . .
. . . . .
当打开该文件,我怎么把它转换为字符串?
像这样:
". . . . .\n
. . . . .\n
. x . . .\n
. x x . .\n
. . . . .\n
. . . . .\n"
答
此方法读取一个文件:
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);
}
+0
愚蠢的问题 - 这是怎么比'新字符串(Files.readAllBytes(f.toPath()))'?这肯定是**更长时间...... –
目前还不清楚你的意思 - 这有点听起来像你想创建一个字符串文字,但是你不能有多行字符串文字(不是没有明确地连接这些行,反正)。 –
'新的字符串(Files.readAllBytes(f.toPath()))' –
@ElliottFrisch值得一提这里的文件编码 - 平台默认可能不正确。虽然它的内容不应该有太大的影响。 –