android 4中文件操作

来源:互联网 发布:lol mac 国服 52pj 编辑:程序博客网 时间:2024/05/18 23:28


package com.example.fileaccess;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/*1、apk中有两种资源文件,使用两种不同的方式进行打开使用。只能读不能写
 raw使用InputStream in = getResources().openRawResource(R.raw.test);
 asset使用InputStream in = getResources().getAssets().open(fileName);

 这些数据只能读取,不能写入。更重要的是该目录下的文件大小不能超过1M。

 

 2、SD卡中的文件使用FileInputStream和FileOutputStream进行文件的操作。
 3、存放在数据区(/data/data/..)的文件只能使用openFileOutput和openFileInput进行操作。
 注意不能使用FileInputStream和FileOutputStream进行文件的操作。
 4、RandomAccessFile类仅限于文件的操作,不能访问其他IO设备。它可以跳转到文件的任意位置,从当前位置开始读写。

 5、InputStream和FileInputStream都可以使用skip和read(buffre,offset,length)函数来实现文件的随机读取。*/

public class MainActivity extends Activity {

 private String str = "";

 private TextView txt;

 private EditText sources;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  txt = (TextView) findViewById(R.id.textView1);
  
  sources=(EditText)findViewById(R.id.sources);
 }

 // 获取raw下 eclipse编辑的文字
 public void getRaw(View v) {
  try {
   InputStream inx = getResources().openRawResource(R.raw.tempraw);
   int length = inx.available();
   byte[] buffer = new byte[length];
   inx.read(buffer);
   // 由于编辑器使用的是utf
   str = EncodingUtils.getString(buffer, "utf8");
   inx.close();

   txt.setText(str);

  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 // 获取外面编辑的文字
 public void getRaw2(View v) {
  try {
   InputStream inx = getResources().openRawResource(R.raw.temp2);
   int length = inx.available();
   byte[] buffer = new byte[length];
   inx.read(buffer);
   // 外面直接用记事本建的文件默认是GBK
   str = EncodingUtils.getString(buffer, "gbk");
   inx.close();

   txt.setText(str);

  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 // 获取asset的文字
 public void asset(View v) {
  String fileName = "temp.txt"; // 文件名字

  try {

   // 得到资源中的asset数据流
   InputStream in = getResources().getAssets().open(fileName);

   int length = in.available();
   byte[] buffer = new byte[length];

   in.read(buffer);
   in.close();
   str = EncodingUtils.getString(buffer, "gbk");
   txt.setText(str);
  } catch (Exception e) {

   e.printStackTrace();

  }
 }

 // 往data/data/包名/写文件

 public void wtapp(View v) {

  if (sources.getText().length()>0)
  {
   try {
    
    writeFile("beyond.txt", sources.getText().toString());
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  else {
   Toast.makeText(MainActivity.this, "孔的",
     Toast.LENGTH_LONG).show();
  }

 }

 // 从data/data/包名/读 文件

 public void readapp(View v) {

  try {
   str = readFile("beyond.txt");
   txt.setText(str);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 // 往sd写文件

 /*
  * 我们在使用SDcard进行读写的时候 会用到Environment类下面的几个静态方法
  *
  * 1: getDataDirectory() 获取到Android中的data数据目录 2:getDownloadCacheDirectory()
  * 获取到下载的缓存目录 3:getExternalStorageDirectory() 获取到外部存储的目录 一般指SDcard
  * 4:getExternalStorageState() 获取外部设置的当前状态 一般指SDcard,
  * android系统中对于外部设置的状态,我们比较常用的应该是 MEDIA_MOUNTED(SDcard存在并且可以进行读写)
  * MEDIA_MOUNTED_READ_ONLY (SDcard存在,只可以进行读操作) 当然还有其他的一些状态,可以在文档中进行查找到
  * 5:getRootDirectory() 获取到Android Root路径 6:i***ternalStorageEmulated()
  * 返回Boolean值判断外部设置是否有效 7:i***ternalStorageRemovable()
  * 返回Boolean值,判断外部设置是否可以移除
  */

 public void writesd(View v) {

  if (sources.getText().length()>0)
  {
   
 
  if (ExistSDCard()) {
   try {

    String saveDir = Environment.getExternalStorageDirectory()
      + "/porktemp1/";
    Log.v("zms", "临时路径:" + saveDir);

    File dir = new File(saveDir);
    if (!dir.exists()) {
     Log.v("zms", "新建目录:" + saveDir);
     dir.mkdir();
     dir.setReadable(true);
     dir.setWritable(true);
    }

    File file = new File(dir + "/test.txt");

    // 删除老文件
    if (file.exists()) {
     try {
      Log.v("zms", "删除文件:" + file.getAbsolutePath());
      file.delete();
     } catch (Exception e) {
      Log.v("zms", "删除文件失败");
      e.printStackTrace();
     }
    }

    // 创建文件
    try {
     Log.v("zms", "创建文件:" + file.getAbsolutePath());
     file.createNewFile();

     if (file.exists()) {
      file.setReadable(true);
      file.setWritable(true);
      String temp = sources.getText().toString();
      FileOutputStream outstream = new FileOutputStream(file);
      outstream.write(temp.getBytes());
      outstream.close();
     }

    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     Log.v("zms", e.toString() + e.getMessage());
     Toast.makeText(MainActivity.this, "文件创建失败",
       Toast.LENGTH_LONG).show();
     return;
    }

   } catch (Exception e) {
    Log.v("zms", e.toString());
   }

  } else {
   Toast.makeText(MainActivity.this, "没有找到SD卡", Toast.LENGTH_LONG)
     .show();

  }
  }
  else {
   Toast.makeText(MainActivity.this, "孔的", Toast.LENGTH_LONG)
   .show();
  }

 }

 // 读取 sd卡
 public void readsd(View v) {

  if (ExistSDCard()) {
   try {

    String saveDir = Environment.getExternalStorageDirectory()
      + "/porktemp1/";
    File file = new File(saveDir + "/test.txt");
    Log.v("zms", "读取的文件路径:"+file.getAbsolutePath());
    
    if (!file.exists()) {
     Toast.makeText(MainActivity.this, "没有找到文件",
       Toast.LENGTH_LONG).show();
     return;
    }

    file.setReadable(true);
    
      FileInputStream inputStream=new FileInputStream(file);
      byte[] buffer=  new byte[1024];
       ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
       int len=0;
       while ((len=inputStream.read(buffer))!=-1)
       {
         outputStream.write(buffer,0,len);
       }
    byte[] data=outputStream.toByteArray();
    outputStream.close();
    inputStream.close();
   
    str = EncodingUtils.getString(data, "utf-8");
    txt.setText(str);

   } catch (Exception e) {
    Log.v("zms", e.toString());
   }

  } else {
   Toast.makeText(MainActivity.this, "没有找到SD卡", Toast.LENGTH_LONG)
     .show();

  }

 }

 private boolean ExistSDCard() {
  if (android.os.Environment.getExternalStorageState().equals(
    android.os.Environment.MEDIA_MOUNTED)) {
   return true;
  } else
   return false;
 }

 // 写数据到包名下
 public void writeFile(String fileName, String writestr) throws IOException {
  try {

   FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

   byte[] bytes = writestr.getBytes();

   fout.write(bytes);

   fout.close();
  }

  catch (Exception e) {
   e.printStackTrace();
  }
 }

 // 程序包下面读取文件
 public String readFile(String fileName) throws IOException {
  String res = "";
  try {
   FileInputStream fin = openFileInput(fileName);
   int length = fin.available();
   byte[] buffer = new byte[length];
   fin.read(buffer);
   res = EncodingUtils.getString(buffer, "utf-8");
   fin.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return res;

 }

}





0 0