您的位置:首页 > 移动开发 > Android开发

【android基础】android文件操作

2013-06-21 14:37 99 查看
activity_main.xml

<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" >

<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>


MainActivity.java

package com.example.android.sample4;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.util.EncodingUtils;

public class MainActivity extends Activity {
TextView tv1;
public static final String ENCODING = "UTF-8";
String fileName = "test.txt";
String message = "你好,这是一个关于文件I/O的示例。";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)this.findViewById(R.id.tv1);
writeFileData(fileName,message);
String result = readFileData(fileName);
tv1.setText(result);
}

public void writeFileData(String fileName,String message)
{
try
{
FileOutputStream fout = openFileOutput(fileName,MODE_PRIVATE);
byte[] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}catch(Exception e)
{
e.printStackTrace();
}
}

public String readFileData(String fileName)
{
String result = "";
try
{
FileInputStream fin = openFileInput(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
fin.close();
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}


也可以把文件放到assets文件夹下,然后通过以下代码读取:

public String getFromAsset(String fileName)
{
String result = "";
try
{
InputStream fin = getResources().getAssets().open(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
fin.close();
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: