2013-05-04 73 views
0

我搜索了几天,我发现所有使用bufferedReader从内部存储上的文件读取。是不是可以使用InputStream从内部存储上的文件读取?使用InputStream从内部存储读取文件

private void dailyInput() 
{  
    InputStream in; 
    in = this.getAsset().open("file.txt"); 
    Scanner input = new Scanner(new InputStreamReader(in)); 
    in.close(); 
} 

我现在使用这个与input.next()来搜索我的文件,我需要的数据。它一切正常,但我想将新文件保存到内部存储并从它们读取,而无需将所有内容都更改为bufferedReader。这是可能的还是我需要咬下子弹并改变一切?仅供参考,我不需要写,只能阅读。

回答

-1

写入文件。

String FILENAME = "file.txt"; 
String string = "hello world!"; 

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

阅读

void OpenFileDialog(String file) { 

    //Read file in Internal Storage 
    FileInputStream fis; 
    String content = ""; 
    try { 
     fis = openFileInput(file); 
     byte[] input = new byte[fis.available()]; 
     while (fis.read(input) != -1) { 
     } 
     content += new String(input); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

content将包含您的文件数据。

+0

要访问设备的内部存储上的文件,我需要设置文件名字符串file.txt的所有设备上的路径?另外,fis.read();只能读入int? – cfitzer 2013-05-04 16:28:19

+0

fis.read()只能读入一个int。此外,我得到一个运行时错误使用这种方法(可能做错了路径)。我正在使用扫描仪在文档中搜索我需要的数据。这允许我一次读取一个字符串。是否可以将Scanner与内部存储器中的文件一起使用? – cfitzer 2013-05-04 17:03:17

+0

k。我正在编辑我的答案,看看它 – Ayush 2013-05-04 17:07:13

0

当您面临从内部存储器中的子文件夹读取文件的情况时,您可以尝试使用以下代码。有时你可能会遇到openFileInput问题,你试图传递上下文。 这里是功能。

public String getDataFromFile(File file){ 
    StringBuilder data= new StringBuilder(); 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     String singleLine; 
     while ((singleLine= br.readLine()) != null) { 
      data.append(singleLine); 
      data.append('\n'); 
     } 
     br.close(); 
     return data.toString(); 
    } 
    catch (IOException e) { 
     return ""+e; 
    } 
}