我有一个构造函数如下:
MyClassName(File f) throws Exception;
和txt文件如下所示:
. . . . .
. . . . .
. x . . .
. x x . .
. . . . .
. . . . .
打开文件时,如何将其转换为String?
像这样:
". . . . .\n
. . . . .\n
. x . . .\n
. x x . .\n
. . . . .\n
. . . . .\n"
答案 0 :(得分:0)
此方法读取文件:
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);
}