java - 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
并且该框为空。我在哪里犯错?
非常感谢您的帮助!
解决方案
要读取保存的数据,请使用此方法使用,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
推荐阅读
- android - 配备 Android 10 的三星 Galaxy S10e:显示键盘时应用程序崩溃
- node.js - 如何从多部分表单数据中获取 Node JS 中间件中的请求正文?
- reactjs - 使用 react-sortable-hoc 拖动时会丢失 tr 元素的样式
- python-3.x - 使用 sudo 运行 python 脚本时,我收到模块“boto3”没有属性“客户端”错误
- wso2 - WSO2IS 5.9 用户存储列表
- php - 如何使用可变参数打开“引导模式对话框”
- ruby-on-rails - WriteXLSX gem 不打印日期格式正确打印为正常数字格式
- c# - 何时是在 Prism 中加载数据的合适时间
- python - 在Python中数据框中一列的特定字符之前提取值
- python - Django:一次更新多个字段