CSV文件无法在Android中阅读

时间:2016-05-18 06:47:26

标签: android csv android-studio

我正在尝试打开下载到内部存储空间的CSV文件,仅供阅读。这是我用过的代码:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.io.FileInputStream;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void onClick(View v) {
    try {
        String FileName = "/storage/emulated/0/Download/MyDocument.csv";
        FileInputStream fis = openFileInput(FileName);
        fis.read();
        fis.close();
        Toast.makeText(getBaseContext(),"File Access Permitted",Toast.LENGTH_SHORT).show();

    }

    catch (Exception e) {
        Toast.makeText(getBaseContext(),"File Access Denied",Toast.LENGTH_SHORT).show();
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

} 

在下载文件并且我能够在文件管理器中打开它时,上面的代码不起作用。如何实现所需的功能?

1 个答案:

答案 0 :(得分:2)

根据stackoverflow question's接受的答案,你可以试试这个:

public String readFileFromDownloads(String fileName) {
    File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    if (!downloadsDir.exists()) return null;

    File file = new File(downloadsDir, fileName);
    if (!file.exists()) return null;

    try {
        StringBuilder fileContent = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line;
        while ((line = br.readLine()) != null) {
            fileContent.append(line);
            fileContent.append('\n');
        }
        br.close();

        return fileContent.toString();
    } catch (IOException ex) {
        //Handle error
        return null;
    }
}

然后从readFileFromDownloads("MyDocument.csv");方法中调用onClick();

此外,您可能需要将android.permission.READ_EXTERNAL_STORAGE添加到您的Manifest,并根据Android Docs处理Android 6.0新权限系统。