200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Android手机数据读写方法(内部存储 SD卡 网络加载 包内文件读取)

Android手机数据读写方法(内部存储 SD卡 网络加载 包内文件读取)

时间:2019-12-02 19:20:13

相关推荐

Android手机数据读写方法(内部存储 SD卡 网络加载 包内文件读取)

本次实例以文本和图片为例,展示了Android手机内部存储的读写方法、SD卡的读写方法,包内文件的读取,以及网络文本及图片的加载与下载。

项目文件在此:文档下载传送门

从网络加载图片或保存到本地。通过字符流进行读写。

Activity文件:

public class HttpImageActivity extends AppCompatActivity {private ImageView show;private Button download,save;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_http_image);show = (ImageView) findViewById(R.id.show);download = (Button) findViewById(R.id.download);save = (Button) findViewById(R.id.download2);download.setOnClickListener(new View.OnClickListener() {String[] strings= {"/thumb300/8ecc236cgw1evrrnv99jqj20qh0zkh7u.jpg"};@Overridepublic void onClick(View view) {new showImg().execute(strings);}});show.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {savePicture();}});save.setOnClickListener(new View.OnClickListener() {String[] strings= {"/img/forum/12/05/20e93j9j809wcwz9hb.jpg"};@Overridepublic void onClick(View view) {new downLoadImg().execute(strings);}});}public class showImg extends AsyncTask<String,Void,Bitmap> {//onPreExecute在主线程中执行命令,它会在doInBackground前执行。//通常会在这里做进度条的初始化,例如:下载进度@Overrideprotected void onPreExecute() {super.onPreExecute();}// int a = 5;//必须实现的方法,可以理解成,在子线程中执行命令@Override//这里的...代表数组protected Bitmap doInBackground(String... strings) {HttpURLConnection httpURLConnection = null;InputStream is = null;Bitmap bitmap = null;try {URL url = new URL(strings[0]);httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(5*1000);httpURLConnection.setReadTimeout(5*1000);/*http 响应码200:成功404:未找到500:发生错误*/if(httpURLConnection.getResponseCode()==200){is=httpURLConnection.getInputStream();bitmap = BitmapFactory.decodeStream(is);//a=100;return bitmap;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(httpURLConnection!=null){httpURLConnection.disconnect();}}return null;}//在UI线程(主线程)中执行命令@Overrideprotected void onPostExecute(Bitmap bitmap) {super.onPostExecute(bitmap);show.setImageBitmap(bitmap);// Toast.makeText(getBaseContext(),""+this.a,Toast.LENGTH_SHORT).show();}}public class downLoadImg extends AsyncTask<String,Void,Bitmap> {//onPreExecute在主线程中执行命令,它会在doInBackground前执行。//通常会在这里做进度条的初始化,例如:下载进度@Overrideprotected void onPreExecute() {super.onPreExecute();}// int a = 5;//必须实现的方法,可以理解成,在子线程中执行命令@Override//这里的...代表数组protected Bitmap doInBackground(String... strings) {HttpURLConnection httpURLConnection = null;InputStream is = null;Bitmap bitmap = null;try {URL url = new URL(strings[0]);httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(5*1000);httpURLConnection.setReadTimeout(5*1000);/*http 响应码200:成功404:未找到500:发生错误*/if(httpURLConnection.getResponseCode()==200){is=httpURLConnection.getInputStream();bitmap = BitmapFactory.decodeStream(is);//a=100;return bitmap;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(httpURLConnection!=null){httpURLConnection.disconnect();}}return null;}//在UI线程(主线程)中执行命令@Overrideprotected void onPostExecute(Bitmap bitmap) {super.onPostExecute(bitmap);FileOutputStream fos = null;String state = Environment.getExternalStorageState();//判断SD卡是否就绪if (!state.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(getBaseContext(),"SD卡未就绪",Toast.LENGTH_SHORT).show();return;}File file = Environment.getExternalStorageDirectory();File myfile = null;try {myfile = new File(file.getCanonicalPath()+"/图片js.png");fos = new FileOutputStream(myfile);press(pressFormat.PNG,100,fos);Toast.makeText(getBaseContext(),"下载完成",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {try {fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}}}}//将程序中的图片保存到SD卡上public void savePicture(){FileOutputStream fos = null;BitmapDrawable bitmapDrawable = (BitmapDrawable) show.getDrawable();Bitmap bitmap = bitmapDrawable.getBitmap();String state = Environment.getExternalStorageState();//判断SD卡是否就绪if (!state.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();return;}File file = Environment.getExternalStorageDirectory();File myfile = null;try {myfile = new File(file.getCanonicalPath()+"/子望.png");fos = new FileOutputStream(myfile);press(pressFormat.PNG,100,fos);Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {try {fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}}}//老师写的从网上下载图片public class SaveHttpImg extends AsyncTask<String,Void,String> {@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected String doInBackground(String... strings) {HttpURLConnection httpURLConnection = null;InputStream is = null;Bitmap bitmap = null;try {URL url = new URL(strings[0]);httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(5 * 1000);httpURLConnection.setReadTimeout(5 * 1000);File root = Environment.getExternalStorageDirectory();FileOutputStream fos = new FileOutputStream(root + "/http.jpg");if (httpURLConnection.getResponseCode() == 200) {is = httpURLConnection.getInputStream();int next = 0;byte[] bytes = new byte[1024];while ((next = is.read(bytes)) > 0) {fos.write(bytes, 0, next);}fos.flush();fos.close();return root + "/http.jpg";}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (httpURLConnection != null) {httpURLConnection.disconnect();}}return null;}@Overrideprotected void onPostExecute(String s) {super.onPostExecute(s);if(!s.equals("")){Toast.makeText(HttpImageActivity.this,"保存路径:"+s,Toast.LENGTH_SHORT).show();} else {Toast.makeText(HttpImageActivity.this,"保存失败:"+s,Toast.LENGTH_SHORT).show();}}}}

Layout文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".sharedpreferences.HttpImageActivity"android:orientation="vertical"><ImageViewandroid:layout_width="match_parent"android:layout_height="300dp"android:id="@+id/show"android:scaleType="centerCrop"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:id="@+id/download"android:text="加载图片"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:id="@+id/download2"android:text="下载图片"/></LinearLayout>

预览图:

读取raw、assets中的文件,将已有的图片保存到SD卡里,将SD卡的图片加载到应用里。

Activity文件:

public class ReadRawAndAssetsActivity extends AppCompatActivity {private Button raw,assets,save,read;private TextView show;private ImageView img,showImg;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_read_raw_and_assets);raw = (Button) findViewById(R.id.bt1);assets = (Button) findViewById(R.id.bt2);save = (Button) findViewById(R.id.bt3);read = (Button) findViewById(R.id.bt4);show = (TextView) findViewById(R.id.tv1);img = (ImageView) findViewById(R.id.iv1);showImg = (ImageView) findViewById(R.id.iv2);raw.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {show.setText(readRaw());}});assets.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {show.setText(readAssets());}});save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {savePicture();}});read.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {readPicture();}});}//读取Raw文件夹public String readRaw(){StringBuilder sbd = new StringBuilder();BufferedReader reader = null;InputStream is = null;is = getResources().openRawResource(R.raw.settings);reader = new BufferedReader(new InputStreamReader(is));String row = "";try {while ((row = reader.readLine())!=null){sbd.append(row);sbd.append("\n");}Toast.makeText(this,"读取成功",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {try {reader.close();} catch (IOException e) {e.printStackTrace();}}return sbd.toString();}//读取Assets文件夹public String readAssets(){StringBuilder sbd = new StringBuilder();BufferedReader reader = null;InputStream is = null;String row = "";try {is = getResources().getAssets().open("cityinfo");reader = new BufferedReader(new InputStreamReader(is));while ((row = reader.readLine())!=null){sbd.append(row);sbd.append("\n");}Toast.makeText(this,"读取成功",Toast.LENGTH_SHORT).show();} catch (IOException e) {Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();} finally {try {reader.close();} catch (IOException e) {e.printStackTrace();}}return sbd.toString();}//将程序中的图片保存到SD卡上public void savePicture(){FileOutputStream fos = null;BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();Bitmap bitmap = bitmapDrawable.getBitmap();String state = Environment.getExternalStorageState();//判断SD卡是否就绪if (!state.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();return;}File file = Environment.getExternalStorageDirectory();File myfile = null;try {myfile = new File(file.getCanonicalPath()+"/机器人.png");fos = new FileOutputStream(myfile);press(pressFormat.PNG,100,fos);Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {try {fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}}}//将图片从SD卡上读取出来显示到ImageView上public void readPicture(){String path = Environment.getExternalStorageDirectory()+"/mei01.jpg";//方法一:根据URI 加载图片// showImg.setImageURI(Uri.parse(path));//方法二:通过BitmapFactory的静态方法 decodeFile(),参数为图片路径。Bitmap bitmap = BitmapFactory.decodeFile(path);showImg.setImageBitmap(bitmap);//方法三:通过BitmapFactory的静态方法 decodeStream(),//参数为 输入流 InputStream;// BitmapFactory.decodeStream();}}

Layout文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".sharedpreferences.ReadRawAndAssetsActivity"android:orientation="vertical"><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:scrollbars="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="200dp"android:id="@+id/tv1"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:gravity="center"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="读取Raw"android:id="@+id/bt1"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="读取Assets"android:id="@+id/bt2"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="保存图片"android:id="@+id/bt3"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="读取图片"android:id="@+id/bt4"/></LinearLayout><ImageViewandroid:layout_width="match_parent"android:layout_height="200dp"android:scaleType="centerCrop"android:id="@+id/iv1"android:src="@mipmap/ic_launcher"/><ImageViewandroid:layout_width="match_parent"android:layout_height="200dp"android:scaleType="centerCrop"android:id="@+id/iv2"android:src="@mipmap/ic_launcher"/></LinearLayout></ScrollView></LinearLayout>

预览图:

在EditView中输入文字,然后将其通过 FileOutputStream 保存到手机SD卡根目录,并且有读取该文件和删除该文件。

Activity文件:

public class SaveToSdCardActivity extends AppCompatActivity {private Button save,read,delete;private EditText content;private TextView show;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_save_to_sd_card);save = (Button) findViewById(R.id.save);read = (Button) findViewById(R.id.read);delete = (Button) findViewById(R.id.del);show = (TextView) findViewById(R.id.show);content = (EditText) findViewById(R.id.content);save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {saveFile();}});read.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {show.setText(readFile());}});delete.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {removeFile();}});}//保存文件到SD卡public void saveFile(){FileOutputStream fos = null;//获取SD卡状态String state = Environment.getExternalStorageState();//判断SD卡是否就绪if (!state.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(this,"请检查SD卡",Toast.LENGTH_SHORT).show();return;}//取得SD卡根目录File file = Environment.getExternalStorageDirectory();try {Log.d("====SD卡根目录:",""+file.getCanonicalPath().toString());//输出流的构造参数1:可以是 File对象 也可以是文件路径//输出流的构造参数2:默认为false=>覆盖内容;true=>追加内容File myfile = new File(file.getCanonicalPath()+"/SD.txt");fos = new FileOutputStream(myfile,true);String str = content.getText().toString();fos.write(str.getBytes());Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {if (fos!=null){try {fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}}}}//从SD卡 读取文件public String readFile(){BufferedReader reader = null;FileInputStream fis = null;StringBuilder sbd = new StringBuilder();String statu = Environment.getExternalStorageState();if(!statu.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();return "";}File root = Environment.getExternalStorageDirectory();try {fis = new FileInputStream(root+"/SD.txt");reader = new BufferedReader(new InputStreamReader(fis));String row = "";while ((row = reader.readLine())!=null){sbd.append(row);}} catch (FileNotFoundException e) {Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();} catch (IOException e) {e.printStackTrace();} finally {if(fis!=null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return sbd.toString();}//从SD卡中删除文件public void removeFile(){String[] files = fileList();File myfile = null;String statu = Environment.getExternalStorageState();if(!statu.equals(Environment.MEDIA_MOUNTED)){Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();}File root = Environment.getExternalStorageDirectory();try {myfile = new File(root.getCanonicalPath()+"/SD.txt");myfile.delete();} catch (IOException e) {Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();}}}

Layout文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".sharedpreferences.SaveToSdCardActivity"android:orientation="vertical"><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="请输入内容"android:id="@+id/content"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:gravity="center"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/save"android:text="保存"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/read"android:text="读取"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/del"android:text="删除"/></LinearLayout><TextViewandroid:layout_width="match_parent"android:layout_height="100dp"android:id="@+id/show"/></LinearLayout>

预览图:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。