简体   繁体   English

访问内部存储中创建的文件

[英]Accessing the file created in internal storage

I decided to save a file using internal storage into a folder. 我决定使用内部存储将文件保存到文件夹中。 My code is: 我的代码是:

File dir = new File (getFilesDir(), "myFolder");
dir.mkdirs();
File file = new File(dir, "myData.txt");

try {
    FileOutputStream f = new FileOutputStream(file);
    PrintWriter pw = new PrintWriter(f);
    pw.println("Hi");
    pw.println("Hello");
    pw.flush();
    pw.close();
    f.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();

} catch (IOException e) {
    e.printStackTrace();
}   
tv.append("\n\nFile written to "+file);

The directory shown is data/data/packageName/file/myFolder/myData.txt However, I wanted to check whether the file contains the strings inputted but i can't seem to find where the created file is. 显示的目录是data / data / packageName / file / myFolder / myData.txt但是,我想检查文件是否包含输入的字符串,但我似乎找不到所创建文件的位置。 I tried to output the contents of the file but i failed. 我试图输出文件的内容,但是我失败了。 I know this sounds ridiculous. 我知道这听起来很荒谬。 All i wanna do is to check the contents and also know whether a file is created or not. 我想做的就是检查内容并知道是否创建了文件。 Can anybody please help? 有人可以帮忙吗?

Open a input stream from the file and read line by line. 从文件打开输入流,并逐行读取。

FileInputStream f = new FileInputStream(new File(getFilesDir()+"/myFolder/"+"myData.txt"));
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while (dis.available() != 0) {
    System.out.println(dis.readLine());
}

Add this code at the end, 最后添加此代码,

try {
        File file = new File(dir, "myData.txt");
        Scanner sc = new Scanner(file);

        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM