这篇文章给大家分享的是有关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文件常见存储与读取操作的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。