gpt4 book ai didi

java.io.FileNotFoundException : Using Object Output & Input Stream

转载 作者:行者123 更新时间:2023-12-02 11:25:35 25 4
gpt4 key购买 nike

我被困在这个问题上有一段时间了,没有任何线索。我正在尝试编写一些对象来为我正在制作的应用程序编写文件,但不断收到文件未找到异常。以下是我正在使用的写入和读取方法。

我收到日志说读取正在开始,但之后我收到错误并且没有收到更多日志。

private void loadData() throws IOException, ClassNotFoundException {
// Will run and load all data from the config file into the app's memory
Log.d("READ:", "reading starting");
FileInputStream fileInputStream = new FileInputStream("config");
ObjectInputStream oIS = new ObjectInputStream(fileInputStream);
Object[] output = new Object[4];

for (int i=0; i<4; i++) {
output[i] = oIS.readObject();
Log.d("READ:", output[i].toString());
}

oIS.close();
fileInputStream.close();

return;
}

public void writeData() throws IOException {
FileOutputStream fOut = openFileOutput("config", Context.MODE_PRIVATE);
ObjectOutputStream oOut = new ObjectOutputStream(fOut);
Log.d("writeData:", "streamsOpened");

oOut.writeInt(this.targetINR);
oOut.writeObject(this.inrReadings);
oOut.writeObject(this.weeklyDoses);
oOut.writeObject(this.alarmTime);
Log.d("writeData:", "objectsWritten");
oOut.close();
fOut.close();
Log.d("writeData:", "Streams closed, write finished");

return;
}

这是调用这些方法的代码。

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);

inrReadings = new HashMap<Calendar, Integer>();
weeklyDoses = new HashMap<Calendar, Integer>();
TextView debug = (TextView) findViewById(R.id.textView) ;
debug.setText("Vars init");

targetINR = 2;
inrReadings.put(Calendar.getInstance(), 2);
weeklyDoses.put(Calendar.getInstance(), 2);
alarmTime = Calendar.getInstance();;

isStoragePermissionGranted();

/* try {
writeData();
} catch (IOException e) {
e.printStackTrace();

debug.setText(debug.getText() + " errorWrite");
Log.d("writeData:", "ioException");
}

try {
loadData();
} catch (IOException e) {
e.printStackTrace();
Log.d("readData:", "ioException");
debug.setText(debug.getText() + " errorRead");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("readData:", "ioException");
debug.setText(debug.getText() + " errorClassNotFound");
}

*/ }

以下是两种权限检查方法:

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("Perms:","Permission is granted now");
return true;
} else {

Log.v("Perms:","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("Perms:","Permission is granted already");
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v("Perms:","Permission: "+permissions[0]+ "was "+grantResults[0]);

// User has granted the access. Now you can initiate the file writing.
try {
writeData();
} catch (IOException e) {
e.printStackTrace();

Log.v("Write:", "ioError");
}

MediaScannerConnection.scanFile(this,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});

try {
loadData();
} catch (IOException e) {
e.printStackTrace();
Log.v("Read:", "ioError");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.v("Read:", "ClassNotFound");
}
}
}

完整错误日志位于:https://pastebin.com/dhxnXyUg

新错误日志:https://pastebin.com/Nq0Kh1Au

**编辑:

通过解决方法修复了该问题,请参阅答案。**

最佳答案

我认为您尚未在 AndroidManifest.xml 文件中添加以下权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如果您的设备使用的是最新版本的 Android SDK,那么您还必须请求用户的许可。以下是您如何向用户请求写入外部存储的权限。

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {

Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);

// User has granted the access. Now you can initiate the file writing.
writeData();
}
}

更新

我可以看到您在文件创建后立即尝试访问该文件。如果这样做,您需要在访问新创建的文件之前扫描文件。

// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});

我认为您需要修改您的 writeData 函数,如下所示。

public void writeData() throws IOException {
FileOutputStream fOut = openFileOutput("config", Context.MODE_PRIVATE);
ObjectOutputStream oOut = new ObjectOutputStream(fOut);
Log.d("writeData:", "streamsOpened");

oOut.writeInt(this.targetINR);
oOut.writeObject(this.inrReadings);
oOut.writeObject(this.weeklyDoses);
oOut.writeObject(this.alarmTime);
Log.d("writeData:", "objectsWritten");
oOut.close();
fOut.close();
Log.d("writeData:", "Streams closed, write finished");

MediaScannerConnection.scanFile(this,
new String[]{"/data/data/" + "com.example.yourpackage" + "/config" }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
}
});

return;
}

并且 loadData 函数应该是。

private void loadData() throws IOException, ClassNotFoundException {
// Will run and load all data from the config file into the app's memory
Log.d("READ:", "reading starting");
FileInputStream fileInputStream = new FileInputStream("/data/data/" + "com.example.yourpackage" + "/config");
ObjectInputStream oIS = new ObjectInputStream(fileInputStream);
Object[] output = new Object[4];

for (int i=0; i<4; i++) {
output[i] = oIS.readObject();
Log.d("READ:", output[i].toString());
}

oIS.close();
fileInputStream.close();

return;
}

com.example.yourpackage 替换为您的项目的包名称。

关于java.io.FileNotFoundException : Using Object Output & Input Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49657460/

25 4 0