Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android/java 讀寫文件

Android/java 讀寫文件

編輯:關於Android編程

讀內存卡的文件

讀取圖片,視頻等媒體文件byte流,

public static byte[] readStream(String imagepath) throws Exception {
		FileInputStream fs = new FileInputStream(imagepath);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while (-1 != (len = fs.read(buffer))) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		fs.close();
		return outStream.toByteArray();
	}

讀取文本文件,用Strng保存


	public String readFile(String filename)
	{
	   String content = null;
	   File file = new File(filename); //for ex foo.txt
	   try {
	       FileReader reader = new FileReader(file);
	       char[] chars = new char[(int) file.length()];
	       reader.read(chars);
	       content = new String(chars);
	       reader.close();
	   } catch (IOException e) {
	       e.printStackTrace();
	   }
	   return content;
	}


寫圖片,視頻等媒體文件,必須用byte[]來寫

	public void writeFile(String filePath,byte[] f){
		try {
			FileOutputStream out = new FileOutputStream(new File(filePath));
			out.write(f);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

       
	}


寫文本文件,寫log信息都可以

	public void writeFile(String filePath,String f){
		FileWriter fw;
		try {
			fw = new FileWriter(filePath);
			fw.write(f);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

       
	}



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved