gpt4 book ai didi

java - Android Studio - 将用户信息保存在 CSV 文件中并读取

转载 作者:行者123 更新时间:2023-11-30 05:07:33 26 4
gpt4 key购买 nike

我是 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 编码

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

关于java - Android Studio - 将用户信息保存在 CSV 文件中并读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com