Android的阅读从文本文件 [英] android reading from a text file

查看:101
本文介绍了Android的阅读从文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它从一个文本文件中使用一个缓冲的阅读器读取一些数据,并返回一个Java类的数据作为一个哈希图:

I have a java class where it reads some data from a text file using a buffered reader and returns that data as a hash map:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class FrequencyLoader {

     public FrequencyLoader() throws FileNotFoundException {
        }

        public HashMap<String, Double> loadUnigramFrequencies() throws FileNotFoundException, IOException {
            HashMap<String, Double> unigramFrequencies = new HashMap<String, Double>();
            String line;
            String[] splittedLine;

            BufferedReader bf = new BufferedReader(new FileReader("unigramFrequencies.txt"));

            while ((line = bf.readLine()) != null) {
                splittedLine = line.split("\\s");


                unigramFrequencies.put(splittedLine[0].trim(), Double.parseDouble(splittedLine[1].trim()));
            }

            return unigramFrequencies;
        }
}

我想用在我的Andr​​oid应用程序,但是当我在Android Activity类创建这个类的一个实例,并且尝试执行loadUnigramFrequencies()函数,我得到一个错误,应用程序意外停止。我想对三星Galaxy S2运行它。如果文件中的某个地方放置在Android项目,而不是在磁盘上?如果是在哪里?

I want to use that in my android application but when I create an instance of this class and try to execute the loadUnigramFrequencies() function in the android Activity class I am getting an error that the application has stopped unexpectedly. I am trying to run it on Samsung Galaxy S2. Should the file be placed somewhere in the android project rather than on the disk? if yes then where?

推荐答案

我认为该错误很可能是有:

I think the error might well be there :

BufferedReader bf = new BufferedReader(new FileReader("unigramFrequencies.txt"));

您应该在这里提供一个绝对路径,并首先确保该文件访问之前存在的的处理异常。

You should provide an absolute path here and first make sure that the file exists before accessing it or handle the exception.

如果该文件是一些最后的资产,你应该把它放在你的项目资产的文件夹,并从那里得到的FileReader。

If this file is some final asset, you should place it in your project assets folder and get a filereader from there.

示例(从这里):

AssetFileDescriptor descriptor = getAssets().openFd("unigramFrequencies.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());

请注意,您的unigramFrequencies.txt文件应为present在&LT;项目&GT; /资产/目录

Note that your unigramFrequencies.txt file should be present in your <project>/assets/ directory

这篇关于Android的阅读从文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆