use*_*496 10 java android java-io
嗨,我刚开始学习android开发,我正在尝试构建一个从文件中读取文本的应用程序.我一直在网上搜索,但我似乎没有找到这样做的方式,所以我有几个问题..
1.怎么做?在android中逐行读取文件的首选方法是什么?
2.我应该在哪里存储文件?它应该在raw文件夹中还是在assets文件夹中?
所以这就是我已经尝试过的:"(我认为问题可能在于找到文件..)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filereader);
try {
// open the file for reading
InputStream fis = new FileInputStream("text.txt");
// if file the available for reading
if (fis != null) {
// prepare the file for reading
InputStreamReader chapterReader = new InputStreamReader(fis);
BufferedReader buffreader = new BufferedReader(chapterReader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
// do something with the line
System.out.println(line);
} while (line != null);
}
} catch (Exception e) {
// print stack trace.
} finally {
// close the file.
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
TyM*_*arc 31
取决于您打算如何处理该文件.如果您的目标只是读取文件,那么资产文件夹就是您的选择.如果要在使用完该文件后将信息存储在该文件中,则应将其放在设备上.
如果选择选项编号2,则需要确定是否希望其他应用程序读取该文件.可在此地址找到更多信息:
http://developer.android.com/training/basics/data-storage/files.html
否则,您可以使用标准的java过程直接读/写设备,就像您描述的那样.虽然,文件路径可能是
"/sdcard/text.txt"
编辑:
这是开始使用的一些代码
FileInputStream is;
BufferedReader reader;
final File file = new File("/sdcard/text.txt");
if (file.exists()) {
is = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
}
Run Code Online (Sandbox Code Playgroud)
但它假设你知道你已经把text.txt你的SD卡的根目录.
如果文件位于assets文件夹中,则必须执行以下操作:
BufferedReader reader;
try{
final InputStream file = getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
} catch(IOException ioe){
ioe.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32331 次 |
| 最近记录: |