六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 41|回复: 0

操作SD卡上的文本文件

[复制链接]

升级  35.2%

212

主题

212

主题

212

主题

进士

Rank: 4

积分
676
 楼主| 发表于 2013-1-15 02:26:16 | 显示全部楼层 |阅读模式
代码是没有在AndroidMenifest.xml中设置权限的前提下对SD卡上的文件进行写,删除操作的例子:
奉上代码:
package cn.com;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import android.app.Activity;import android.os.Bundle;import android.widget.Button;import android.view.View;import android.view.View.OnClickListener;public class SdCardEx extends Activity implements OnClickListener {File file;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Button delete = (Button) findViewById(R.id.delete);delete.setOnClickListener(this);file = new File("/sdcard/1.txt");//判断文件是否存在if (file.exists()) {System.out.println("file exists");try {FileOutputStream fos = new FileOutputStream("/sdcard/1.txt");fos.write("Hello World!".getBytes());fos.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif (file.exists()) {file.delete();}}}
2.main.xml文件布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="@string/hello" /><Button android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="delete" android:id="@+id/delete" /></LinearLayout>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表