我正在使用下一个方法从文件中读取内容。这里的问题是我仅限于为 inputBuffer
指定的字符数(在本例中为 1024)。
首先,如果内容长度小于1024个字符,我会得到很多空白字符,我需要使用trim来删除它们。
其次,也是更重要的一点,我想读取文件的全部内容,即使它超过 1024 个字符,并将其插入到 String
对象中。我知道我不应该使用 .available
方法来确定文件中是否有更多数据,因为它不准确或类似的东西。
关于我应该如何去做这件事有什么想法吗?
public String getContent( String sFileName )
{
//Stop in case the file does not exists
if ( !this.exists( sFileName ) )
return null;
FileInputStream fIn = null;
InputStreamReader isr = null;
String data = null;
try{
char[] inputBuffer = new char[1024];
fIn = _context.openFileInput(sFileName);
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fIn.close();
}catch(IOException e){
e.printStackTrace(System.err);
return null;
}
return data.trim();
}
最佳答案
您可以在分配缓冲区之前读取#/bytes:
// Poor
char[] inputBuffer = new char[1024];
fIn = _context.openFileInput(sFileName);
isr = new InputStreamReader(fIn);
// Better
long nbytes = new File(sFileName).length();
char[] inputBuffer new char[nbytes];
isr = new InputStreamReader (
_context.openFileInput (sFileName));
另一种解决方案是将输入作为字符串读取,一次一行。
关于java - 安卓。从文件中读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12328555/