java.io.FileNotFoundException:使用Object Output&输入流

时间:2018-04-04 17:54:42

标签: java android android-studio

现在已经坚持了一段时间并且毫无头绪。我正在尝试写一些对象来存档我正在制作的应用程序,但一直得到文件未找到异常。以下是写& amp;的方法。读到我正在使用。

我得到日志说read正在启动,但之后我得到错误并且不再获取日志。

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");
    }

* /     }

以下是两种permision检查方法:

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

**编辑:

通过解决方法修复它,查看答案。**

2 个答案:

答案 0 :(得分:1)

我认为您尚未在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替换为您的项目包名称。

答案 1 :(得分:0)

我最终修复了它,没有实现onRequestPermision()等。我只是通过让它只写一个对象(一个对象数组)来简化对象写入。该数组具有存储在其中的所有值。一点办法,但它简化了写作过程!