推荐阅读:
Android 通过HttpURLConnection访问Http协议网络
Android SQlite数据库使用详解
Android xUtils框架最全使用详解
Android 动态权限最全解析
其中raw
下的和asserts
下的文件可以以资源文件的形式读取,这些目录的数据只能读取,不能写入,两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制。
data/data/包名
和sdcard
目录文件可读可写。其中data/data/包名
目录不需要申请权限,sdcard
目录需要申请权限
Android工程默认是没有raw
文件夹的在读文件前我们先把raw
文件夹以及文件建好
res
目录 右键New
-> Directory
-> 弹窗中输入raw
raw
目录 右键New
-> File
-> 弹窗中输入test.txt
test.txt
文件 ,往里面输入hello world
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
//得到资源中的Raw数据流
inputStream = getResources().openRawResource(R.raw.test);
reader = new InputStreamReader(inputStream);// 字符流
bufferedReader = new BufferedReader(reader); //缓冲流
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android工程默认是没有assets
文件夹的,在读文件前我们先把assets
文件夹以及文件建好
New
-> Folder
-> Assets Folder
Assets Folde
目录 右键New
-> File
-> 弹窗中输入test.txt
test.txt
文件 ,往里面输入hello world
assets
文件中的数据方法 InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
//得到资源中的asset数据流
inputStream = getResources().getAssets().open("test.txt");
reader = new InputStreamReader(inputStream);// 字符流
bufferedReader = new BufferedReader(reader); //缓冲流
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将数据以普通文件的形式保存在 /data/data/包名
中,该方法不需要申请权限。
存放在数据区(/data/data/包名
)的文件可以使用openFileOutput
和openFileInput
进行操作。
也可以直接指定文件/data/data/包名
路径读写。
该目录存放文件类型规则如下:
路径 | 功能 |
---|---|
data/data/包名/shared_prefs |
存放SharedPreferences数据 |
data/data/包名/databases |
存放数据库数据 |
data/data/包名/files |
存放普通数据 |
data/data/包名/cache |
存放缓存文件 |
方法1:openFileOutput
FileOutputStream fileOutputStream = null;
try {
String text = "hello world";
fileOutputStream = openFileOutput("test.txt", MODE_PRIVATE);
fileOutputStream.write(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
openFileOutput
方法参数详解
@Override
public FileOutputStream openFileOutput(String name, int mode)
throws FileNotFoundException {
}
参数值 | 参数含义 |
---|---|
Context.MODE_PRIVATE | 指定该文件数据只能被本应用程序读、写 |
Context.MODE_WORLD_READABLE | 指定该文件数据能被其他应用程序读,但不能写 |
Context.MODE_WORLD_WRITEABLE | 指定该文件数据能被其他应用程序读 |
Context.MODE_APPEND | 该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件; |
方法2:传统方法读写
String text = "hello world";
File file1=new File("/data/data/com.lucashu.file/","test.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file1);
fileOutputStream.write(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法1:openFileInput
FileInputStream fileInputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
fileInputStream = openFileInput("test.txt");
reader = new InputStreamReader(fileInputStream);// 字符流
bufferedReader = new BufferedReader(reader); //缓冲流
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法2:openFileInput
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
File file=new File("/data/data/com.lucashu.file/", "test.txt");
inputStream = new FileInputStream(file);
reader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
从打印的结果中我们可以看出数据读取成功
getFilesDir();// data/data/包名/files 目录
getFilesDir().getParent(),;// data/data/包名/ 目录
sdcard
读写的数据将数据保存在 /mnt/sdcard
目录,该目录读写需要先申请动态权限,动态权限申请方法如下
首先需要在manifest.xml
中添加权限
如果是AndroidQ
或者更高的版本还需要在manifest.xml
文件中的application
节点下加入
android:requestLegacyExternalStorage="true"
申请动态权限方法:
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"};
private void checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
}
//申请权限
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
} else {
Toast.makeText(this, "已授权成功!", Toast.LENGTH_SHORT).show();
writeSdcard();
}
}
Activity中动态权限的回调方法
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_EXTERNAL_STORAGE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
writeSdcard();
} else {
Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
private void writeSdcard() {
String text = "hello world";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File storage = Environment.getExternalStorageDirectory();
File tmepfile = new File(storage.getPath());
if (! tmepfile.exists()) {
tmepfile.mkdirs();
}
File file1=new File(tmepfile,"test.txt");
if (!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file1);
fileOutputStream.write(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private void readSdcard() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
File storage = Environment.getExternalStorageDirectory();
File tmepfile = new File(storage.getPath());
File file=new File(tmepfile, "test.txt");
inputStream = new FileInputStream(file);
reader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
package com.lucashu.file;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
}
private void writeSdcard() {
String text = "hello world";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File storage = Environment.getExternalStorageDirectory();
File tmepfile = new File(storage.getPath());
if (! tmepfile.exists()) {
tmepfile.mkdirs();
}
File file1=new File(tmepfile,"test.txt");
if (!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file1);
fileOutputStream.write(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private void readSdcard() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
InputStream inputStream = null;
Reader reader = null;
BufferedReader bufferedReader = null;
try {
File storage = Environment.getExternalStorageDirectory();
File tmepfile = new File(storage.getPath());
File file=new File(tmepfile, "test.txt");
inputStream = new FileInputStream(file);
reader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(reader);
StringBuilder result = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result.append(temp);
}
Log.i("MainActivity", "result:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"};
private void checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
}
//申请权限
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
} else {
Toast.makeText(this, "已授权成功!", Toast.LENGTH_SHORT).show();
readSdcard();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_EXTERNAL_STORAGE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
readSdcard();
} else {
Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
作者:lucashu
出处:https://blog.csdn.net/huweiliyi/category_8913738.html
原创不易,欢迎转载,但未经作者同意请保留此段声明,并在文章页面明显位置给出原文链接。