2012-06-11 25 views
2

你好,我有一个很烦人的问题 我想读取文本文件与此类似的Android - 阅读使用扫描文件,怎么去文件

KEY 
0 1 2 3 4 5 6 7 
KEYEND 

我试图用扫描器类,因为它可以返回结果为字符串,小数,无论

public static void LoadStuff(String Name) { 
     Scanner reader = null; 
     try { 
     reader = new Scanner(new File(Name)); 
     } catch (Exception e) { 
     Log.d("damn", "FAIL"); 
     } 
     if(reader != null) 
      Load(reader); 
    } 


private static void Load(Scanner reader) { 
     while (reader.hasNext()) { 
     String result = reader.next(); 
     if (result == "KEY") { // may be result.equalsignorecase 
      while (result != "KEYEND") { 
       int index = reader.nextInt(); 
       Log.d("Index", String.valueOf(index)); 
      } 
     } 
     } 
      reader.close(); 
    } 

我不能做以上,导致扫描仪无法找到该文件,解析像“file.txt的”不工作,也试图与路径 这样的“RES/data/file.txt“也不起作用 我应该在哪里把文件以及如何获得该目录,使其工作 感谢

回答

1

,我一直用来访问我的当前项目中的文件(文字文件)的代码:

textFileStream = new DataInputStream(getAssets().open(String.format("myFile.txt"))); 

您可以随时用自己填充的字符串填充String.format部分。

的关键一直是

getAssets() 

一部分。

所以你的情况,你可能有一些看起来如下:

reader = new Scanner(new File(getAssets().open(String.format("myFile.txt")))); 

OR 

reader = new Scanner(new File(getAssets().open(Name))); 

文件的构造可以在一个的InputStream中,getAssets()打开将返回一个InputStream。

+0

做工精良,谢谢 – nullpointer

+0

很高兴我能帮助回答你的问题:-) – trumpetlicks

0

将您的文本文件放在assets文件夹中,然后使用getAssets().open("file.txt")读取它。

Example

+0

作品就像我想要的,谢谢你 – nullpointer

+0

如果您可以接受的答案将是巨大的。请参阅http://stackoverflow.com/faq#reputation – nhaarman

0
  1. 先给这样"/sdcard/file.txt"

  2. 并请总是你 “equals” 进行比较时,对象路径。 Never use "==" or "!=" with Objects. (String is an object too in Java)

    如:

    if (result.equals("KEY"))` {  // equals is used 
        `while (!(result.equals("KEYEND")))` { // !equals is used 
    
         int index = reader.nextInt(); 
         Log.d("Index", String.valueOf(index)); 
        } 
    } 
    
0

将文件写入到内部存储使用openFileOutput。根据Android的Data Storage DOC:

String FILENAME = "hello_file"; 
String string = "hello world!"; 

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
fos.write(string.getBytes()); 
fos.close(); 

要使用扫描仪读取文件:

File f = new File(getFilesDir(), FILENAME); 
Scanner s = new Scanner(f); 

注:getFilesDir()返回到文件与openFileOutput(字符串创建的文件系统的目录的绝对路径,INT )被存储。

要查看输出到您的文件的内容,请查看:is it possible to see application data from adb shell the same way I see it mounting SD card?

其他Storage Options

3

此代码使用您的类的getAssets()方法。您需要将文本文件放置在Android项目的资产文件夹中。 getAssets方法返回一个AssetManager对象。 open(String.format(“filename.txt”))方法返回一个InputStream。 InputStream是DataInputStream的参数。然后,将其用作扫描仪的输入。

try { 
    DataInputStream textFileStream = new DataInputStream(getAssets().open(String.format("filename.txt"))); 
    Scanner sc = new Scanner(textFileStream); 
    while (sc.hasNextLine()) { 
     String aLine = sc.nextLine(); 
     System.out.println(aLine); 
    } 
     sc.close(); 
} catch (IOException e) { 
     e.printStackTrace(); 
}