這篇文章給大家分享的是有關Android編程中File文件常見存儲與讀取操作的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
具體如下:
MainActivity文件代碼如下:
package example.com.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class MainActivity extends Activity
{
final String FILE_NAME = "test.txt";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(new StringBuilder("a").append("b").append("c")
.toString());
// 獲取兩個按鈕
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
// 獲取兩個文本框
final EditText edit1 = (EditText) findViewById(R.id.edit1);
final EditText edit2 = (EditText) findViewById(R.id.edit2);
// 為write按鈕綁定事件監聽器
write.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View source)
{
// 將edit1中的內容寫入文件中
write(edit1.getText().toString());
edit1.setText("");
}
});
read.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// 讀取指定文件中的內容,并顯示出來
edit2.setText(read());
}
});
}
private String read()
{
try
{
// 打開文件輸入流
FileInputStream fis = openFileInput(FILE_NAME);
byte[] buff = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder("");
while ((hasRead = fis.read(buff)) > 0)
{
sb.append(new String(buff, 0, hasRead));
}
return sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private void write(String content)
{
try
{
// 以追加模式打開文件輸出流
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
// 將FileOutputStream包裝成PrintStream
PrintStream ps = new PrintStream(fos);
// 輸出文件內容
ps.println(content);
ps.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}布局文件代碼如下:
<!--?xml version="1.0" encoding="utf-8"?--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/edit1" android:layout_width="match_parent" android:layout_height="wrap_content" android:lines="4"/> <Button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="write"/> <EditText android:id="@+id/edit2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:editable="false" android:lines="4"/> <Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="read"/> </LinearLayout>
感謝各位的閱讀!關于“Android編程中File文件常見存儲與讀取操作的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。