首页 > 解决方案 > AndroidStudio - 将用户信息保存在 CSV 文件中并读取

问题描述

我是 Android Studio 编程的新手。我正在尝试创建一个简单的应用程序来获得基本经验。在应用程序中,我需要将单个输入存储到内部存储器中的文件(最好是 CSV)中。首先,我正在尝试保存用户数据——我的姓名和电话号码。保存方法如下所示:

public void save(View view)
    {
        String fileName = "user.csv";
        ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
        File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
        File file = new File(directory, fileName);

        String data = "FirstName,LastName,PhoneNumber";
        FileOutputStream outputStream;
        try {
            outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
            outputStream.write(data.getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

数据似乎已保存,我被重定向到MainActivity. 这是方法:

protected void onCreate(Bundle savedInstanceState) {
    File file = new File(getFilesDir(),"user.csv");
    if(!file.exists()) {
        Intent intent = new Intent(this, activity_login.class);
        startActivity(intent);
    }
    else {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv_name = findViewById(R.id.tv_name);
        TextView tv_phone = findViewById(R.id.tv_phone);

        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("user.csv"));
            while ((sCurrentLine = br.readLine()) != null) {
                tv_name.setText(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

没有存储任何值,TextView tv_name并且该框为空。我在哪里犯错?

非常感谢您的帮助!

标签: javaandroidfilecsv

解决方案


要读取保存的数据,请使用此方法使用,UTF_8 ENCODING

public static String readAsString(InputStream is) throws IOException {
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            reader = new BufferedReader(new InputStreamReader(is,UTF_8));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return sb.toString();
}

使用此方法如下,解析文件“user.csv”。

public static String readFileAsString(File file) throws IOException {
    return readAsString(new FileInputStream(file));
}

获取字符串并设置 textView


推荐阅读