我正在尝试将数据从我的应用程序保存到文件中,而不是将此文件保存在我的PC上。我已经阅读了很多关于外部存储上文件创建的教程。按照本指南,我创建了以下代码。手机没有SD卡,外部存储器位于内部存储器中。所以有我的问题:使用" writeFunc"后文件存在,但它是空的。没有任何异常被抛出。 我用所有现有的标志尝试了这个部分,遗憾的是没有结果:
FileOutputStream fOut = openFileOutput(fileStruct.getName(),MODE_WORLD_READABLE);
setReadable和setWritable函数以" false"返回,但没有例外。
我该怎么办?
package com.track.fos;
//imports are okay
public class MainActivity extends AppCompatActivity {
public TextView textBox;
private File fileStruct;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBox = (TextView) findViewById(R.id.textView);
textBox.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString());
fileStruct = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "lufiTestFile.txt" );
}
public void writeFunc(View view) {
textBox.append("\nFilestruct to string: " + fileStruct.toString());
Log.d("External storage state", Environment.getExternalStorageState(fileStruct));
try {
boolean stateInfo = fileStruct.exists();
textBox.append("\nexist: " + stateInfo);
if( !stateInfo ){
//stateInfo = fileStruct.mkdirs();
//textBox.append("\nmake dirs: " + stateInfo);
stateInfo = fileStruct.createNewFile();
textBox.append("\ncreateNewFile: " + stateInfo);
}
stateInfo = fileStruct.setReadable( true , false);
textBox.append("\nsetReadable: " + stateInfo);
stateInfo = fileStruct.setWritable( true, false );
textBox.append("\nsetWritable: " + stateInfo);
FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);
fOut.write("Test text hopefuly inside the file.".getBytes());
fOut.flush();
fOut.close();
textBox.append("\nFile written");
} catch (Exception e) {
e.printStackTrace();
Log.d("File write throws",e.getCause().toString());
textBox.append("\nFile write failed");
}
}
public void readFunc(View view) {
try {
FileInputStream fin = openFileInput( fileStruct.getName() );
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
textBox.append("\n" + temp);
} catch (Exception e) {
e.printStackTrace();
textBox.append("\nFile read failed");
}
}
}
答案 0 :(得分:1)
FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);
这不会为external storage上的文件打开FileOutputStream
。 openFileOutput()
写信给internal storage。
将其替换为:
FileOutputStream fOut = new FileOutputStream(fileStruct);
您还需要ensure that the file gets indexed, so other apps and desktop OSes can see it。