作者givemepass (〆)
看板AndroidDev
標題Re: [問題] 讀取文字檔(/raw;/assets;/res)
時間Wed Dec 28 15:51:54 2011
※ 引述《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
→ aleelyle:可以直接讀寫 12/28 16:00
→ givemepass:請問樓上大大 怎麼直接讀寫 12/28 16:09
→ nonebelieve:java 讀檔有很多種方法 google就有 12/28 16:24
nonebelieve大 我知道JAVA有很多讀檔方式 所以不知道是否可以提供關鍵字
讓我了解有什麼方法可以直接從ANDROID讀文字檔? 謝謝
推 sweet00914:感謝各位的建議~0.0 12/28 16:39
→ sweet00914:請問各位能提供採用RandomAccessFile來讀取assets中的 12/28 16:40
→ sweet00914:在assets中的*.txt檔案嗎?0.0 12/28 16:40
→ sweet00914:givemepass大大是透過SD卡來存取~請問aleelyle大大 12/28 16:41
→ sweet00914:怎直接讀取呢?(RandomAccessFile直接讀取/assets/*.txt 12/28 16:42
※ 編輯: givemepass 來自: 61.221.115.4 (12/28 16:48)
→ aleelyle:Acticity.getAssets.open 12/28 19:59
→ aleelyle: v 12/28 19:59
這位大大 請問跟我寫的有什麼不一樣?@@ 還是你沒看內文?
※ 編輯: givemepass 來自: 61.64.168.114 (12/28 20:12)