我想重新访问在android studio中创建的文件。我在堆栈交换中找到了以下代码片段
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
根据我的理解,这会在下载文件夹中创建一个名为“myData.txt”的文件。我想做的是将“文件”传递给另一个方法中的函数,如此
public void onLocationChanged(Location location) {
ArrayList<Location> list = new ArrayList<>();
list.add(location);
GPX.writePath(file,"hello",list);
}
如何在不实际创建新文件的情况下创建一个能够访问txt文件的文件变量?
答案 0 :(得分:0)
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
实际上它不会创建物理文件。它只是在内存中创建一个对象(由file
引用)。
然后,您可以使用方法中的引用来写入物理文件,如下所示:
public void onLocationChanged(File location) throws IOException {
ArrayList<File> list = new ArrayList<>();
list.add(location);
writeToFile("Text", location);
}
private static void writeToFile(String text, File file)
throws IOException {
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(text);
}
}
如果要在方法中使用引用,可以将file
引用传递给您的方法,该方法应该有一些代码将文本写入实际文件中:
GPX.writePath(file,"hello",list);
...
public static void writePath(File file, String n, List<Location> points) throws IOException {
...
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(n);
}
}