当我试图将数据写入android中的文件时

时间:2015-11-26 06:17:08

标签: android

我正在尝试将我的modelclass数据写入json文件,这是我的代码

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Name:"
        android:textSize="21dp"
        android:id="@+id/txtName" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editName"
        android:hint="Name"
        android:paddingLeft="10dp"
        android:textColorHint="@color/colorAccent"/>
    <View
        android:layout_width="wrap_content"
        android:layout_height="25dp"></View>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="City:"
        android:textSize="21dp"
        android:id="@+id/txtCity" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editCity"
        android:hint="City"
        android:paddingLeft="10dp"
        android:textColorHint="@color/colorAccent"/>

    <View
        android:layout_width="wrap_content"
        android:layout_height="25dp"></View>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Mobile:"
        android:textSize="21dp"
        android:id="@+id/txtMobile" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:ems="10"
        android:paddingLeft="10dp"
        android:id="@+id/editMobile"
        android:hint="Mobile"
        android:textColorHint="@color/colorAccent"/>

    <View
        android:layout_width="wrap_content"
        android:layout_height="25dp"></View>

    <Button
        android:id="@+id/btnInsert"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:text="Insert"
        android:textSize="21dp"
        android:textColor="#FFFFFF"
        android:background="@color/colorAccent"/>
</LinearLayout>

这里,我的模型类是Student.java

package model;

import java.io.Serializable;

/**
 * Created by MY WORLD on 11/26/15.
 */
public class Student implements Serializable {

    private int id;
    private String name;
    private String city;
    private String phno;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {

        this.city = city;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhno() {
        return phno;
    }

    public void setPhno(String phno) {
        this.phno = phno;
    }

    @Override
    public String toString() {
        return "Student[id="+id+"name="+name+"city="+city+"phno="+phno+"]";
    }
}

这是我的mainActivity.java

package com.domore.jsonserialization;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import model.Student;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText name,city,mobile;
    Button insert;
    int id=1;
    FileOutputStream fos=null;
    BufferedOutputStream bos=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        name=(EditText)findViewById(R.id.editName);
        city=(EditText)findViewById(R.id.editCity);
        mobile=(EditText)findViewById(R.id.editMobile);

        insert=(Button)findViewById(R.id.btnInsert);

        insert.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {

        Student std=new Student();
        std.setId(id);
        std.setName(name.getText().toString());
        std.setCity(city.getText().toString());
        std.setPhno(mobile.getText().toString());

        Gson gson=new Gson();

        String json=gson.toJson(std);

        Log.e("name:",std.getName());
        Log.e("json Data",""+json);
        try{

            fos=new FileOutputStream("D:\\Student.json");
            byte b[]=json.getBytes();
            fos.write(b);
            fos.close();
        }
        catch (FileNotFoundException ffe){
            ffe.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            try{
                fos.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

我有2个错误如下

第一次错误

11-26 11:18:08.680 2608-2608/? W/System.err: java.io.FileNotFoundException: D:\Student.json: open failed: EROFS (Read-only file system)
11-26 11:18:08.680 2608-2608/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:456)
11-26 11:18:08.680 2608-2608/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
11-26 11:18:08.680 2608-2608/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:127)
11-26 11:18:08.680 2608-2608/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:116)
11-26 11:18:08.681 2608-2608/? W/System.err:     at com.domore.jsonserialization.MainActivity.onClick(MainActivity.java:63)

第二次错误

FATAL EXCEPTION: main
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime: Process: com.domore.jsonserialization, PID: 2608
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileOutputStream.close()' on a null object reference
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at com.domore.jsonserialization.MainActivity.onClick(MainActivity.java:76)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.view.View.performClick(View.java:4756)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:19749)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5221)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
11-26 11:18:08.682 2608-2608/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
11-26 11:18:08.695 1238-1252/? W/ActivityManager:   Force finishing activity com.domore.jsonserialization/.MainActivity

我该怎么做,建议我解决这个错误

1 个答案:

答案 0 :(得分:0)

这是您读取和写入文件的方式

首先,获取文件对象

您需要存储路径。对于内部存储,请使用:

File path = context.getFilesDir();

对于外部存储(SD卡),请使用:

File path = context.getExternalFilesDir(null);

然后创建文件对象:

File file = new File(path, "my-file-name.txt");

将字符串写入文件

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

或使用Google Guava

Files.write("text-to-write", file, "UTF-8");

将文件读取为字符串

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

或者如果您使用的是Google Guava

String contents = Files.toString(file,"UTF-8");

为了完整起见,我会提到

String contents = new Scanner(file).useDelimiter("\\A").next();

不需要库,但基准测试比其他选项慢50%-400%(在我的Nexus 5的各种测试中)。

备注

对于这些策略中的每一个,都会要求您捕获IOException。

Android上的默认字符编码是UTF-8。

如果您使用外部存储空间,则需要添加到您的清单中:

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

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

写入权限意味着读取权限,因此您不需要两者。