我正在创建一个应用程序,它从内存中复制文件(工作)然后读取它并显示文件中的信息。该文件采用csv格式,当我尝试从文件中显示文本时,所有非英文字符都显示为 。因此,我用Notepad ++打开它,我看到当我尝试UTF-8编码时记事本显示应该存在的字符,表明它应该可以被Android应用程序读取。 这是我用来复制文件的代码:
//called in the main activity
Intent myIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
myIntent.setType("text/*");
myIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(myIntent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
Uri result= data.getData();
Log.e("fag", result.getPath() + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
copyFile(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
Log.e("", "canceled");
}
}
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
}
private void copyFile(Uri uri) {
FileOutputStream out = null;
try {
InputStream in = getContentResolver().openInputStream(uri);
out = openFileOutput(NAME , MODE_PRIVATE);
byte[] buffer = new byte[1024];
while ( in.read(buffer) != -1) {
out.write(buffer);
}
in.close();
in = null;
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
fnfe1.printStackTrace();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
然后我使用列表视图显示文件,并使用以下代码读取缓冲区:
BufferedReader br = null;
try {
File a = new File(getFilesDir().getPath() + "/CSV_RAW");
if(a.isFile())Log.e("TEST", "file exists");
br = new BufferedReader(new FileReader(a.getPath()));
int count = 0;
String ln;
while((ln =br.readLine()) != null)
{
if (ln.indexOf(',') != -1)
count++;
}
br = new BufferedReader(new FileReader(a.getPath()));
ln= br.readLine() ;
arr = new String[count];
count = 0;
while((ln = br.readLine()) != null)
{
if (ln.indexOf(',') != -1){
arr[count] = getName(ln);
count ++;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
我想知道如何修复它或者是否存在更深层次的问题。
答案 0 :(得分:0)
解决方案是写和读utf8是使用BufferedReader / BufferedWriter与InputStreamReader / OutputStreamWriter如下
//reading utf8
BufferedReader br = new BufferedReader(new InputStreamReader(in /*your FileInoutStream*/ , "utf8"),1024 /* buffer size */);
//writing utf8
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out /*your FileOutputStream */, "utf8"),1024 /* buffer size */);