java - 读取文本文件方法

标签 java android file text

我是一个 android 新手,如果这看起来微不足道,而且这篇文章很长,我深表歉意。我用谷歌搜索等,但我能找到的唯一 android 引用似乎是指

InputStream is = getAssets().open("read_asset.txt");
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

我尝试在类里面使用它,但即使在导入 java.io.InputStream 之后也是如此;它在 getAssets() 上出错。

我正在尝试使用 ListView 的 rowId 点击; 打开一个文本文件(取决于 rowId 值), 逐行读取文件, 生成前 16 个字符的字符串数组,等等 然后使用数组填充下一个 Activity 的 ListView 。

String[] sectID = null; //to be loaded in listview
    switch (rowId){
        case 0://custom, go to section input screen
        case 1:                 
     readSectionFile s = new readSectionFile("Sect_US.dat");
     sectID=s.arrayShapesAll();

我的 readSectionFile 类(提取)是;

public readSectionFile(String FileName) {
  //Count the number of section records in the data file
  String line = null;    // String that holds current file line
  int recordcount = 0;   // Line number of count
  try{
      BufferedReader buf = new BufferedReader(new FileReader(FileName));
      // Read file to count records
      while ((line = buf.readLine()) != null){    //null = EOF
          line = buf.readLine();
          if (line.substring(0, 1).equals("*") || line.length() == 0) {      //== comment or blank line
              //do nothing
          }else{
              recordcount++;
          }
      }//while
      buf.close();
  }catch (IOException x){
       x.printStackTrace();
  }//end try
  // Now read file to load array
  mSectionIDArray = new String[recordcount + 1];
  mSectionIdx = new int[recordcount + 1][2];
  mData = new double[recordcount + 1][15];
  int c=0;
  String sectdata = null;    // String that holds current file line
  try {
      BufferedReader buf = new BufferedReader(new FileReader(FileName));
      while ((sectdata = buf.readLine()) != null){           //null = EOF
          sectdata = buf.readLine();

代码无法运行并在 readSectionFile s = new readSectionFile("Sect_US.dat"); 处崩溃

此外,在 readSectionFile 代码中,buf 的第二个实例生成一个 Eclipse 错误,要求尝试、捕获 block ,而第一个实例被接受。

我的问题是, 我要正确打开这个文本文件(在/assets 中)吗? 第二个buf使用有什么问题?

最佳答案

getAssets() 是 Activity 中的一个方法。如果您尝试从不同的类调用 getAssets(),请将 Activity 的上下文传递到您要调用该方法的类,然后调用 context.getAssets()。

关于java - 读取文本文件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6394884/

相关文章:

java - 我们如何从 JSON 文档中检索所有键及其前缀

java - java.math.BigInteger.bitCount() 的替代品?需要还是不需要?

java - 谁应该调用 ByteBuffer.flip()

android - 从 ListView 中获取位置以外的值

ruby - 为什么 Ruby 中的迭代需要这么长时间?

eclipse - 让 IntelliJ IDEA 刷新项目并检测更改的文件

java - 进行部署时 build 和 dist 目录的目的不同

java - 在打开新 Activity 之前等待旋转动画在 Android 中完成?

android - 是否可以从使用 Android NDK 构建的共享库中删除符号?

windows - 如何使用批处理文件创建系统还原点?