android讀取內存和sd卡中的txt文件

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		readFromMemery("myFile.txt");
		String name = android.os.Environment.getExternalStorageDirectory()
				+ "/myFile.txt";
		readFormSDcard(name);

	}

	/**
	 * @description 讀取sd卡中的txt文件
	 * @param path
	 *            路徑
	 */
	private void readFormSDcard(String path) {

		if (!new File(path).exists()) {
			Log.i("tag", "沒有這個文件");
			System.out.println("沒有文件");
			return;
		} else {
			try {
				FileInputStream fis = new FileInputStream(path);
				@SuppressWarnings("resource")
				BufferedReader br = new BufferedReader(new InputStreamReader(
						fis));
				StringBuilder sb = new StringBuilder("");
				String line = null;
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				Log.i("tag", sb.toString());
				System.out.println(sb.toString());
			} catch (Exception e) {
				Log.i("tag", "讀取失敗!");
				System.out.println(e);
			}
		}
	}

	/**
	 * @description 讀取內存中的txt文件
	 * @param path
	 *            文件路徑
	 */
	private void readFromMemery(String path) {
		try {
			InputStream is = openFileInput(path);
			byte[] buffer = new byte[100];
			int byteCount = is.read(buffer);
			String str = new String(buffer, 0, byteCount, "utf-8");
			Log.i("tag", str);
		} catch (Exception e) {
			Log.i("tag", "讀取失敗!");
		}
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章