?首先在AndroidManifest中添加讀寫權(quán)限:
<!-- 寫外部存儲(chǔ)-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<!-- 讀外部存儲(chǔ)-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- android 10 讀寫sd卡權(quán)限-->
<uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE"
tools:ignore="ProtectedPermissions" />
public class FileWriteReadActivity extends Activity {
private static final String TAG="FileWriteReadActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new_bd_meige);
//將內(nèi)容為"test read file222" 的文本文件baa.txt存到/sdcard目錄下
writeFile("test read file222","/sdcard","baa.txt");
try {
Thread.sleep(3000);
//從/sdcard目錄中讀baa.txt文件中的內(nèi)容
String fileActivateData = getFileActivateData("/sdcard","baa.txt");
Log.e(TAG,"fileActivateData==="+fileActivateData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 寫文本文件到指定目錄下
* @param content 文本內(nèi)容 "test read file222"
* @param rootPath 指定要存放的目錄 此示例中是/sdcard
* @param authName 文件名稱 "baa.txt"
*/
public void writeFile(String content,String rootPath,String authName) {
try {
//判斷實(shí)際是否有SD卡,且應(yīng)用程序是否有讀寫SD卡的能力,有則返回true
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String path = rootPath;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File targetFile = new File(path +"/"+authName);
Log.e("FilePackUtil", "targetFile.getPath()===" + targetFile.getPath());
// 方式一:使用RandomAccessFile是在原有的文件基礎(chǔ)之上追加內(nèi)容,
// RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
// raf.seek(targetFile.length()); //光標(biāo)移到原始文件最后,再執(zhí)行寫入
// raf.write(content.getBytes());
// raf.close();
// 方式二:而使用outputstream則是要先清空內(nèi)容再寫入
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer=content.getBytes();
fileOutputStream.write(buffer, 0, buffer.length);// 開始寫入數(shù)據(jù)到這個(gè)文件。
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取指定目錄下指定文件的內(nèi)容
* @param fileAbsolutePaht 指定的目錄 /sdcard
* @param txtName 指定的文件 "baa.txt"
* @return
*/
private String getFileActivateData(String fileAbsolutePaht,String txtName) {
ArrayList<String> result = new ArrayList<String>();
File file = new File(fileAbsolutePaht);
File[] files = file.listFiles();
if (files != null) {
//篩選指定目錄下是否有指定文件
for (int i = 0; i < files.length; ++i) {
if (!files[i].isDirectory()) {
String fileName = files[i].getName();
if (fileName.equals(txtName)) {
result.add(fileName);
}
}
}
//若有指定文件,則讀文件內(nèi)容
if (result.size() != 0) {
return readTxtFile(fileAbsolutePaht + "/"+ result.get(0));
}
}
return "";
}
/**
* 讀文件中的內(nèi)容
* @param strFilePath /sdcard/baa.txt
* @return
*/
public String readTxtFile(String strFilePath) {
String path = strFilePath;
Log.e("FilePackUtil", "strfilePath===" + path);
String content = ""; //文件內(nèi)容字符串
//打開文件
File file = new File(path);
//如果path是傳遞過來的參數(shù),可以做一個(gè)非目錄的判斷
if (file.isDirectory()) {
Log.d("TestFile", "The FaceAuthFile doesn't not exist.");
} else {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行讀取
while ((line = buffreader.readLine()) != null) {
content += line;
}
instream.close();
}
} catch (java.io.FileNotFoundException e) {
Log.d("TestFile", "The File doesn't not exist.");
} catch (IOException e) {
Log.d("TestFile", e.getMessage());
}
}
return content;
}
}
踩坑提醒:
若報(bào)錯(cuò)/sdcard/....:open failed:EACCES(Permission denied) 則表示沒有權(quán)限向sdcard中寫文件
解決方法:
1、更換文件存儲(chǔ)目錄為外部存儲(chǔ)。如使用getExternalCacheDir(),存放路徑一般是/storage/sdcard/Android/data/<應(yīng)用包名>/cache目錄。?文章來源:http://www.zghlxwxcb.cn/news/detail-684962.html
2、將應(yīng)用打包成系統(tǒng)應(yīng)用。在AndroidManifest.xml 中manifest節(jié)點(diǎn)下添加?android:sharedUserId="android.uid.system",還需要系統(tǒng)簽名。文章來源地址http://www.zghlxwxcb.cn/news/detail-684962.html
到了這里,關(guān)于Android如何寫文件到sdcard目錄或指定目錄,讀指定目錄中指定文件的內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!