Re: [問題] 讀取文字檔(/raw;/assets;/res)
※ 引述《sweet00914 (別理我)》之銘言:
: 請問各位大大~
: Q1:
: 我將一個*.txt放置/raw,/assets中都不會有錯誤產生,
: 可以若我將*.txt放置/res中就會有錯誤。
: 請問這是為什麼呢?
: Q2:
: 若我要使用RandomAccessFile來讀取*.txt
: 方式有兩種
: RandomAccessFile raf = new RandomAccessFile(File file, "r");
: RandomAccessFile raf = new RandomAccessFile(String str, "r");
: 可是我不知道若從/assets和/raw中如何取得file跟str?
: 上述兩個問題~請大家多多指教。0.0
把你的檔案放在assets裡面
我假設你的檔案叫做 my_text_file.txt
然後我複製一份存到sdcard下面/sdcard/text_file.txt
就可以拿這個來讀取
public class TestRandomFileAccessActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//先取得資產管理員
AssetManager assetManager = this.getApplicationContext().getAssets();
try {
//用資產管理員打開文字檔 變成串流
InputStream inputStream = assetManager.open("my_text_file.txt");
byte[] b = new byte[1024];
int len = -1;
File file = new File("/sdcard/text_file.txt");
FileOutputStream outputStream = new FileOutputStream(file);
while((len = inputStream.read(b))!=-1){
//寫到sdcard下 變成一個file
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
//在拿這個file讓RandomAccessFile讀取
RandomAccessFile random = new RandomAccessFile(file,"rw");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
其實如果可以直接從android讀進file, 應該會方便許多,
我這樣做等於多了一個步驟,
不知道還有沒有其他的方法?
如果有麻煩請指導一下 謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.221.115.4
→
12/28 16:00, , 1F
12/28 16:00, 1F
→
12/28 16:09, , 2F
12/28 16:09, 2F
→
12/28 16:24, , 3F
12/28 16:24, 3F
nonebelieve大 我知道JAVA有很多讀檔方式 所以不知道是否可以提供關鍵字
讓我了解有什麼方法可以直接從ANDROID讀文字檔? 謝謝
推
12/28 16:39, , 4F
12/28 16:39, 4F
→
12/28 16:40, , 5F
12/28 16:40, 5F
→
12/28 16:40, , 6F
12/28 16:40, 6F
→
12/28 16:41, , 7F
12/28 16:41, 7F
→
12/28 16:42, , 8F
12/28 16:42, 8F
※ 編輯: givemepass 來自: 61.221.115.4 (12/28 16:48)
→
12/28 19:59, , 9F
12/28 19:59, 9F
→
12/28 19:59, , 10F
12/28 19:59, 10F
這位大大 請問跟我寫的有什麼不一樣?@@ 還是你沒看內文?
※ 編輯: givemepass 來自: 61.64.168.114 (12/28 20:12)
討論串 (同標題文章)