【发布时间】:2015-06-30 22:27:25
【问题描述】:
我想知道这段代码有什么问题:
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
start();
}
public void start(){
File file = new File("file.file");
try{
FileOutputStream fos;
fos = openFileOutput("file.file", Context.MODE_PRIVATE);
BufferedOutputStream bos = new BufferedOutputStream(fos);
if(file.length() == 0){
BigInteger bi = new BigInteger("1000");
bos.write(bi.toByteArray());
bos.flush();
bos.close();
textView.setText(""+file.length()); //This is always 0, why?
}
else{
//do stuff, but since file.length() is always 0, this never happens.
}
}
所以基本上我想检查文件是否为空,如果为空,则向其中添加内容。所以我期望的是,当我下次打开应用程序时,长度不应该是空的,因为我之前已经写过了。但是,文件的长度总是0,这是为什么呢? File.length() 表示它返回字节数。
【问题讨论】:
-
@AndyThomas:正确,删除了我的评论。
-
@optional - 检查您的变量
file是否引用了与您在方法openFileOutput()中打开的文件相同的实际路径。 (更好的是,将变量file传递给openFileOutput(),以消除问题。) -
我刚刚检查了这个,但不幸的是问题仍然存在。 :(
标签: java android file fileoutputstream