1. 文件的基本操作
File类的相关技巧和操作:文件的创建、重命名和删除,文件夹的创建和删除等操作。
1 package control; 2 3 import java.io.File; 4 5 public class FileUtil { 6 public static final String FILE_NAME = "myfile.txt"; 7 public static final String FOlDER_NAME = "NewFolder"+File.separator+"AnotherNewFolder"; 8 9 }
1 package control; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class CreatFile { 7 public static void main(String[] args) { 8 File file = new File(FileUtil.FILE_NAME); 9 if (!file.exists()) { 10 try { 11 file.createNewFile(); 12 System.out.println("文件已经创建了"); 13 } catch (IOException e) { 14 e.printStackTrace(); 15 } 16 } else { 17 System.out.println("文件已经存在!"); 18 System.out.println("文件名为:" + file.getName()); 19 System.out.println("文件的绝对路径为:" + file.getAbsolutePath()); 20 System.out.println("文件的相对路径为:" + file.getPath()); 21 22 System.out.println("文件大小为: " + file.length() + "字节"); 23 System.out.println("文件是否可读:" + file.canRead()); 24 System.out.println("文件是否可写:" + file.canWrite()); 25 } 26 } 27 28 }
1 package control; 2 3 import java.io.File; 4 5 public class RenameFile { 6 public static void main(String[] args) { 7 File file = new File(FileUtil.FILE_NAME); 8 File newFile = new File("anotherFile.txt"); 9 file.renameTo(newFile); 10 System.out.println(newFile); 11 System.out.println(file.getName()); 12 } 13 }
1 package control; 2 3 import java.io.File; 4 5 public class DeleteFile { 6 public static void main(String[] args) { 7 File file = new File(FileUtil.FILE_NAME); 8 if (file.exists()) { 9 file.delete(); 10 System.out.println("文件已经被删除了!"); 11 } 12 } 13 14 }
1 package control; 2 3 import java.io.File; 4 5 public class CreatFolder { 6 7 public static void main(String[] args) { 8 File folder = new File(FileUtil.FOlDER_NAME); 9 if (folder.exists() != true) { 10 folder.mkdirs(); 11 } 12 } 13 }
1 package control; 2 3 import java.io.File; 4 5 public class RemoveFolder { 6 public static void main(String[] args) { 7 File folder = new File(FileUtil.FOlDER_NAME); 8 if (folder.exists()) { 9 folder.delete(); 10 } 11 } 12 13 }
2. 读取Assets中的文件数据
使用getResources().getAssets().open("filename")获取Assets文件夹中的文件数据流 。Assets文件夹在根目录下。注意使用UTF-8编码。
3. 读取raw目录中的文件数据
getResources().openRawResource(fileid)方法获取raw文件夹中文件的数据流 。
1 package com.example.readassets; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.UnsupportedEncodingException; 8 9 import android.app.Activity; 10 import android.content.res.Resources.NotFoundException; 11 import android.os.Bundle; 12 import android.util.Log; 13 import android.view.View; 14 15 public class MainActivity extends Activity { 16 17 private static final String TAG = "ReadAssets"; 18 private static final String TAG_RAW = "RawData"; 19 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 25 findViewById(R.id.btnReadTxt).setOnClickListener( 26 new View.OnClickListener() { 27 28 @Override 29 public void onClick(View v) { 30 try { 31 // InputStream返回的是字节流,因此读取文本文件时,要包装成字符流 32 InputStream is = getResources().getAssets().open( 33 "info.txt"); 34 InputStreamReader isr = new InputStreamReader(is, 35 "UTF-8"); 36 BufferedReader bfr = new BufferedReader(isr); 37 String in = ""; 38 while ((in = bfr.readLine()) != null) { 39 Log.i(TAG, in); 40 } 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 }); 46 47 findViewById(R.id.btnReadRaw).setOnClickListener( 48 new View.OnClickListener() { 49 50 @Override 51 public void onClick(View v) { 52 try { 53 InputStream is = getResources().openRawResource( 54 R.raw.info); 55 InputStreamReader isr = new InputStreamReader(is, 56 "UTF-8"); 57 BufferedReader bfr = new BufferedReader(isr); 58 String inString = ""; 59 while ((inString = bfr.readLine()) != null) { 60 Log.i(TAG_RAW, inString); 61 } 62 } catch (NotFoundException e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 } catch (UnsupportedEncodingException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } catch (IOException e) { 69 // TODO Auto-generated catch block 70 e.printStackTrace(); 71 } 72 73 } 74 }); 75 } 76 77 }
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/container" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 tools:context="com.example.readassets.MainActivity" 7 android:orientation="vertical" 8 tools:ignore="MergeRootFrame" > 9 10 <Button 11 android:id="@+id/btnReadTxt" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content" 14 android:text="读取TXT数据" /> 15 16 <Button 17 android:id="@+id/btnReadRaw" 18 android:layout_width="fill_parent" 19 android:layout_height="wrap_content" 20 android:text="读取RAW数据" /> 21 22 </LinearLayout>
4. 读写内部存储的文件数据
使用openFileOutput()方法获取内部文件的输出流与文件数据的写入,使用openFileInput()获取内部文件的输入流并将数据读取出来。
1 package com.example.readwriteexternaldata; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStreamReader; 9 import java.io.OutputStreamWriter; 10 import java.io.UnsupportedEncodingException; 11 12 import android.app.Activity; 13 import android.os.Bundle; 14 import android.os.Environment; 15 import android.view.View; 16 import android.widget.EditText; 17 import android.widget.TextView; 18 import android.widget.Toast; 19 20 public class MainActivity extends Activity { 21 22 private EditText editText; 23 private TextView txShow; 24 File sdcard = Environment.getExternalStorageDirectory(); 25 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_main); 30 31 editText = (EditText) findViewById(R.id.editText); 32 txShow = (TextView) findViewById(R.id.txShow); 33 34 findViewById(R.id.btnRead).setOnClickListener(new View.OnClickListener() { 35 36 @Override 37 public void onClick(View v) { 38 File myfile = new File(sdcard, "This is my file.txt"); 39 if (myfile.exists()) { 40 FileInputStream fis; 41 try { 42 fis = new FileInputStream(myfile); 43 InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 44 char[] input = new char[fis.available()]; 45 isr.read(input); 46 isr.close(); 47 fis.close(); 48 String inString = new String(input); 49 txShow.setText(inString); 50 } catch (FileNotFoundException e) { 51 e.printStackTrace(); 52 } catch (UnsupportedEncodingException e) { 53 e.printStackTrace(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 } 59 }); 60 61 findViewById(R.id.btnWrite).setOnClickListener(new View.OnClickListener() { 62 63 @Override 64 public void onClick(View v) { 65 File myfile = new File(sdcard, "This is my file.txt"); 66 //如果手机有sd卡,才执行 67 if (!sdcard.exists()) { 68 Toast.makeText(getApplicationContext(), "当前系统不具备SD卡目录", Toast.LENGTH_LONG).show(); 69 return; 70 } 71 try { 72 myfile.createNewFile(); 73 Toast.makeText(getApplicationContext(), "文件创建完成!", Toast.LENGTH_LONG).show(); 74 FileOutputStream fos = new FileOutputStream(myfile); 75 OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); 76 osw.write(editText.getText().toString()); 77 osw.flush(); 78 osw.close(); 79 fos.close(); 80 Toast.makeText(getApplicationContext(), "文件写入完成!", Toast.LENGTH_LONG).show(); 81 82 } catch (IOException e) { 83 e.printStackTrace(); 84 } 85 } 86 }); 87 88 } 89 90 }
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/container" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.readwriteexternaldata.MainActivity" 8 tools:ignore="MergeRootFrame" > 9 10 <EditText 11 android:id="@+id/editText" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content" 14 android:text="输入要保存的数据" 15 android:textAppearance="?android:attr/textAppearanceLarge" /> 16 17 <Button 18 android:id="@+id/btnWrite" 19 android:layout_width="fill_parent" 20 android:layout_height="wrap_content" 21 android:text="写入数据" /> 22 23 <Button 24 android:id="@+id/btnRead" 25 android:layout_width="fill_parent" 26 android:layout_height="wrap_content" 27 android:text="读入数据" /> 28 29 <TextView 30 android:id="@+id/txShow" 31 android:layout_width="fill_parent" 32 android:layout_height="wrap_content" 33 android:text="显示读到的数据" 34 android:textAppearance="?android:attr/textAppearanceLarge" /> 35 36 </LinearLayout>
5. 读取外部存储的文件数据
使用Environment.getExternalStorageDirectory()获取系统SD卡路径,并使用File类进行后续的操作。要获得相应的权限。
点击"写入数据"Button,将上方EditText里面的内容写到文件"This is my file.txt"中;点击"读入数据"Button,将"This is my file.txt"中的内容显示在下面的TextView中。
1 package com.example.readwriteinternaldata; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.io.OutputStreamWriter; 9 import java.io.UnsupportedEncodingException; 10 11 import android.app.Activity; 12 import android.content.Context; 13 import android.os.Bundle; 14 import android.view.View; 15 import android.widget.EditText; 16 import android.widget.TextView; 17 import android.widget.Toast; 18 19 public class MainActivity extends Activity { 20 21 private String fileName = "test"; 22 23 private TextView txShow; 24 private EditText et; 25 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_main); 30 31 et = (EditText) findViewById(R.id.et); 32 txShow = (TextView) findViewById(R.id.txShow); 33 34 findViewById(R.id.btnWrite).setOnClickListener(new View.OnClickListener() { 35 36 @Override 37 public void onClick(View v) { 38 try { 39 FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE); 40 OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); 41 osw.write(et.getText().toString()); 42 //flush可以保证输出缓冲区的内容 43 //注意关闭顺序 44 osw.flush(); 45 fos.flush(); 46 osw.close(); 47 fos.close(); 48 Toast.makeText(getApplicationContext(), "写入完成", Toast.LENGTH_LONG).show(); 49 } catch (FileNotFoundException e) { 50 e.printStackTrace(); 51 } catch (UnsupportedEncodingException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } catch (IOException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } 58 } 59 }); 60 61 findViewById(R.id.btnRead).setOnClickListener(new View.OnClickListener() { 62 63 @Override 64 public void onClick(View v) { 65 try { 66 FileInputStream fis = openFileInput(fileName); 67 InputStreamReader is = new InputStreamReader(fis, "UTF-8"); 68 char input[] = new char[fis.available()]; 69 is.read(input); 70 is.close(); 71 fis.close(); 72 String readed = new String(input); 73 txShow.setText(readed); 74 75 } catch (FileNotFoundException e) { 76 e.printStackTrace(); 77 } catch (UnsupportedEncodingException e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } catch (IOException e) { 81 // TODO Auto-generated catch block 82 e.printStackTrace(); 83 } 84 } 85 }); 86 } 87 88 }
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/container" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.readwriteinternaldata.MainActivity" 8 tools:ignore="MergeRootFrame" > 9 10 <EditText 11 android:id="@+id/et" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content" 14 android:text="在这里输入内容" /> 15 16 <Button 17 android:id="@+id/btnWrite" 18 android:layout_width="fill_parent" 19 android:layout_height="wrap_content" 20 android:text="保存数据" /> 21 22 <Button 23 android:id="@+id/btnRead" 24 android:layout_width="fill_parent" 25 android:layout_height="wrap_content" 26 android:text="读取数据" /> 27 28 <TextView 29 android:id="@+id/txShow" 30 android:layout_width="fill_parent" 31 android:layout_height="wrap_content" 32 android:textAppearance="?android:attr/textAppearanceLarge" /> 33 34 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.readwriteinternaldata" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 <uses-sdk 8 android:minSdkVersion="14" 9 android:targetSdkVersion="19" /> 10 11 <application 12 android:allowBackup="true" 13 android:icon="@drawable/ic_launcher" 14 android:label="@string/app_name" 15 android:theme="@style/AppTheme" > 16 <activity 17 android:name="com.example.readwriteinternaldata.MainActivity" 18 android:label="@string/app_name" > 19 <intent-filter> 20 <action android:name="android.intent.action.MAIN" /> 21 22 <category android:name="android.intent.category.LAUNCHER" /> 23 </intent-filter> 24 </activity> 25 </application> 26 27 </manifest>