【发布时间】:2021-03-24 16:14:25
【问题描述】:
我正在使用 Android Studio 编写一个应用程序,我设置了一个文件选择器,它可以为我提供文件的路径(文件可以在外部或内部存储上)。我需要读取选择的文件,修改它并用另一个名称写在相同的位置。我已经实现了读写功能,但它们不适用于分隔符,因为它们使用 FileInputStream/FileOutputStream,我已经尝试过使用 FileReader 的函数但返回 null。有人如何解决我的问题? 提前致谢!
我的读/写功能:
public String Read_file(String fn, Context context) {
int ch;
String d;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
fis = context.openFileInput(fn);
try {
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Error");
}
return d = new String(fileContent);
}
public void Write_file(String fn, String data, Context context){
FileOutputStream outS;
//Scrive sul file
try {
outS = context.openFileOutput(fn, Context.MODE_PRIVATE);
outS.write(data.getBytes());
outS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我已经尝试过了,但返回 null:
public String t(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
//String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fname));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
我选择的文件:
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode == 10){
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String src = uri.getPath();
String file_name = uri.getLastPathSegment();
String fn = src.substring(src.lastIndexOf('/') + 1);
System.out.println(fn);
//////READ THE FILE AT THE URI
}
}
}
【问题讨论】:
-
“我已经设置了一个文件选择器,它可以为我提供文件的路径(文件可以在外部或内部存储上)”——这究竟是什么意思?您的代码可以读取和写入来自 Android SDK 称为 internal storage 的文件,但不适用于 external storage 或 removable storage。
-
使用文件选择器我可以选择一个文件并返回路径(例如下载文件夹或 sd 卡上),但我需要读取和写入该文件
-
“使用文件选择器,我可以选择一个文件并将路径返回给我”——请编辑您的问题并显示您使用此“文件选择器”的代码。例如,如果您的意思是
ACTION_GET_CONTENT或ACTION_OPEN_DOCUMENT,它们都不是“文件”选择器,并且您都无法获得有用的“路径”。因此,虽然ACTION_GET_CONTENT或ACTION_OPEN_DOCUMENT是正确的解决方案,但您需要使用Uri值,使用ContentResolver和openInputStream()和openOutputStream()等方法。 -
是的,抱歉,我已经用我的文件选择器进行了编辑
标签: java android file read-write