Java位元組流在Android中的使用,java位元組流android

來源:互聯網
上載者:User

Java位元組流在Android中的使用,java位元組流android

轉載請註明出處:http://www.cnblogs.com/cnwutianhao/p/6611252.html 

 

引言:項目開發有時會使用上傳檔案到伺服器,再從伺服器取資料顯示到本地這一過程;或者輸入一段文字,再把文字顯示出來。這個過程都用到了IO流。

IO流分為字元流(Reader\Writer)和位元組流(InputStream\OutputStream)

在位元組流當中,我們經常使用的就是FileInputStream(讀取本地檔案中的位元組資料)和FileOutputStream(將位元組資料寫出到檔案)

本案例我將操作如何使用FileOutputStream(File file)和FileInputStream(String name)

 

先做一下簡單解釋:
FileOutputStream(File file) 建立一個向指定 File 對象表示的檔案中寫入資料的檔案輸出資料流。
FileInputStream(String name) 通過開啟一個到實際檔案的串連來建立一個FileInputStream,該檔案通過檔案系統中的路徑名 name 指定。

 

FileOutputStream(File file)

①檔案轉換成流

系統給出的架構如下:

public FileOutputStream(File file) throws FileNotFoundException {    this(file, false);}

實現步驟:建立檔案路徑、在路徑下建立檔案、將檔案轉換成流

File cacheDir = getApplicationContext().getFilesDir();File file = new File(cacheDir, "test.txt");FileOutputStream fos = null;fos = new FileOutputStream(file);

②字串轉換成byte數組寫入到流中

系統給出的架構如下:

public void write(byte b[]) throws IOException {    write(b, 0, b.length);}

實現步驟:擷取到編輯的文字(用Buffer Knife代替findViewById)、將文字轉換成字串、將 b.length 個位元組從指定 byte 數組寫入此檔案輸出資料流中

@BindView(R.id.editText)EditText editText;String strWrite = editText.getText().toString();fos.write(strWrite.getBytes());

③關閉流

關閉此檔案輸出資料流並釋放與此流有關的所有系統資源

fos.close();

我們在EditText控制項上輸入1,log日誌會給我們返回結果

03-24 14:02:17.591 28576-28576/? E/MainActivity: File為/data/user/0/com.tnnowu.android.iobutterknife/files/test.txt03-24 14:02:17.591 28576-28576/? E/MainActivity: Fos為java.io.FileOutputStream@6eaf805

 

FileInputStream(String name)

①讀取本地檔案中的位元組資料

系統給出的架構如下:

public FileInputStream(String name) throws FileNotFoundException {    this(name != null ? new File(name) : null);}

實現步驟:擷取到檔案路徑、讀取檔案中的位元組資料

String filePath = getApplicationContext().getFilesDir().toString() + File.separator + "test.txt";FileInputStream fis = null;fis = new FileInputStream(filePath);

②將位元組流寫入到byte數組中

系統給出的架構如下:

public int read(byte b[]) throws IOException {    return read(b, 0, b.length);}

實現步驟:從此輸入資料流中將最多 b.length 個位元組的資料讀入一個 byte 數組中。

byte[] buffer = new byte[1024];StringBuilder sb = new StringBuilder();while (fis.read(buffer) != -1) {    sb.append(new String(buffer));}

③關閉流
關閉此檔案輸入資料流並釋放與此流有關的所有系統資源。

fis.close();

我們點擊按鈕,log日誌會給我們返回結果

03-24 14:04:50.048 28576-28576/? E/MainActivity: Buffer為[B@27b505a03-24 14:04:50.048 28576-28576/? E/MainActivity: strRead為1

 

完整代碼(Butter Knife介入):

點擊查看我的另一篇文章Butter knife使用詳解

點擊免費下載DEMO

MainActivity:

package com.tnnowu.android.iobutterknife;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import butterknife.BindView;import butterknife.ButterKnife;import butterknife.OnClick;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private static final String TAG = "MainActivity";    @BindView(R.id.editText)    EditText editText;    @BindView(R.id.btn_write)    Button btnWrite;    @BindView(R.id.bth_read)    Button bthRead;    @BindView(R.id.btn_clear)    Button btnClear;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.bind(this);    }    @OnClick({R.id.btn_write, R.id.bth_read, R.id.btn_clear})    public void onClick(View view) {        switch (view.getId()) {
       // FileOutputStream使用 case R.id.btn_write: String strWrite = editText.getText().toString(); File cacheDir = getApplicationContext().getFilesDir(); File file = new File(cacheDir, "test.txt"); Log.e(TAG, "File為" + file); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); Log.e(TAG, "Fos為" + fos); } catch (FileNotFoundException e) { e.printStackTrace(); } try { fos.write(strWrite.getBytes()); } catch (IOException e) { e.printStackTrace(); } try { fos.close(); } catch (IOException e) { e.printStackTrace(); } break;
       // FileInputStream使用 case R.id.bth_read: String strRead = ""; StringBuilder sb = new StringBuilder(); String filePath = getApplicationContext().getFilesDir().toString() + File.separator + "test.txt"; FileInputStream fis = null; try { fis = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } byte[] buffer = new byte[1024]; Log.e(TAG, "Buffer為" + buffer); try { while (fis.read(buffer) != -1) { sb.append(new String(buffer)); } fis.close(); } catch (IOException e) { e.printStackTrace(); } strRead = new String(sb); Log.e(TAG, "strRead為" + strRead); Toast.makeText(getApplicationContext(), strRead, Toast.LENGTH_LONG).show(); editText.setText(strRead); break; case R.id.btn_clear: editText.setText(""); break; } }}

布局代碼:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.tnnowu.android.iobutterknife.MainActivity">    <EditText        android:id="@+id/editText"        android:layout_width="match_parent"        android:layout_height="100dp"        android:ems="10"        android:inputType="textPersonName"        android:text=""        android:textSize="40sp" />    <Button        android:id="@+id/btn_write"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="寫" />    <Button        android:id="@+id/bth_read"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="讀" />    <Button        android:id="@+id/btn_clear"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="清除" /></LinearLayout>

FileInputStream 和FileOutputStream適用於操作於任何形式的檔案(因為是以位元組為嚮導),如果想要操作文字檔,採用FileInputReader和FileOutputWriter效率更高。

 

關注我的新浪微博,擷取更多Android開發資訊!
關注科技評論家,領略科技、創新、教育以及最大化人類智慧與想象力!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.