【问题标题】:CSV File not opening for reading in AndroidCSV 文件无法在 Android 中打开以供阅读
【发布时间】:2016-05-18 06:47:26
【问题描述】:

我正在尝试打开下载到内部存储中的 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();
    }
}

} 

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

【问题讨论】:

  • 使用一些好的库,比如opencsv.sourceforge.net
  • 怎么不工作了?是否有异常,或者您为查看它是否正常工作所做的任何类型的输出?如果你有堆栈跟踪,请包括你的堆栈跟踪。 openFileInput 的代码是什么?
  • 确实如此。什么不工作?见过敬酒吗?
  • 所以你有一个例外。但你不是在敬酒e.getMessage()。它说什么?烤它。但是你也可以在 LogCat 中找到它。
  • FileInputStream fis = openFileInput(FileName);。那应该是FileInputStream fis = new FileInputStream(FileName);

标签: android csv android-studio


【解决方案1】:

根据这个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;
    }
}

然后从您的onClick(); 方法内部调用readFileFromDownloads("MyDocument.csv");

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2012-04-22
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多