作者:筱美嘚 | 来源:互联网 | 2023-10-11 19:59
小编给大家分享一下Android怎么读写CSV文件,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
前言
Android读写CSV文件的相关内容,CSV也就是Comma-Separated Values逗号分隔的文本文件,
读写csv文件和读写普通文件类似;写的时候给数据之间添加上逗号。
设定存储路径和文件名:
private static final String FILE_FOLDER =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "AboutView" + File.separator + "data";
private static final String FILE_CSV = "about_data.csv";
写CSV文件
使用FileOutputStream来向文件尾部添加数据
FileOutputStream.write(byte[] data)
向文件流写入字节数据。
class WriteData2CSVThread extends Thread {
short[] data;
String fileName;
String folder;
StringBuilder sb;
public WriteData2CSVThread(short[] data, String folder, String fileName) {
this.data = data;
this.folder = folder;
this.fileName = fileName;
}
private void createFolder() {
File fileDir = new File(folder);
boolean hasDir = fileDir.exists();
if (!hasDir) {
fileDir.mkdirs();// 这里创建的是目录
}
}
@Override
public void run() {
super.run();
createFolder();
File eFile = new File(folder + File.separator + fileName);
if (!eFile.exists()) {
try {
boolean newFile = eFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream os = new FileOutputStream(eFile, true);
sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
sb.append(data[i]).append(",");
}
sb.append("\n");
os.write(sb.toString().getBytes());
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
读CSV文件
使用BufferedReader读取每一行内容;读出来的数据带有逗号分隔符
class ReadCSVThread extends Thread {
String fileName;
String folder;
public ReadCSVThread(String folder, String fileName) {
this.folder = folder;
this.fileName = fileName;
}
@Override
public void run() {
super.run();
File inFile = new File(folder + File.separator + fileName);
final StringBuilder cSb = new StringBuilder();
String inString;
try {
BufferedReader reader =
new BufferedReader(new FileReader(inFile));
while ((inString = reader.readLine()) != null) {
cSb.append(inString).append("\n");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mCSVTv.setText(cSb.toString());// 显示
}
});
}
}
以上是“Android怎么读写CSV文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程笔记行业资讯频道!