简体   繁体   English

从不扩展AppCompatActivity的类从Android Studio上的内部存储打开文件

[英]Opening a file from internal storage on Android Studio from a class that doesn't extend AppCompatActivity

Is it possible to read a file from internal storage in a utility class that doesn't extend anything? 是否可以在不扩展任何内容的实用程序类中从内部存储读取文件? I have the code below to read a file, but I can't use the openFileInput method because it doesn't exist. 我有下面的代码来读取文件,但是我不能使用openFileInput方法,因为它不存在。 Is there something I have to import to read these files? 我必须导入一些内容才能读取这些文件吗?

private String readFromFile(String fileName) {
    FileInputStream fis = null;
    try {
        fis = openFileInput("Links"); // this doesn't compile in a utility class
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        return String.valueOf(sb);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

You can use java.io.FileInputStream 您可以使用java.io.FileInputStream

private String readFromFile(String fileName) {
    InputStream in = null;
    try {
        in = new FileInputStream(fileName);
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        return String.valueOf(sb);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

相关问题 如何从适配器类(不扩展 AppCompatActivity)调用 getSupportFragmentManager()? - How to call getSupportFragmentManager() from adapter class (which doesn't extend AppCompatActivity)? 我们如何从Firebase下载Android Studio中的文件(pdf),使其不出现在手机的内部存储中? - How can we download file(pdf) in android studio from firebase such that it doesn't appear in phone's internal storage? 从内部存储,Android Studio(JAVA)播放音频文件的应用程序 - App that plays audio file from internal Storage, Android Studio (JAVA) 我在Android Studio中扩展AppCompatActivity时出错 - Error when i extend AppCompatActivity in Android studio Android从内部存储复制文件到外部 - Android copy file from internal storage to external 从内部存储Android读取文件 - Read file from Internal Storage Android 在Android中将文件从内部存储复制到外部存储 - Copy file from the internal to the external storage in Android android从内部存储中删除文件 - android deleting a file from internal storage 如何从 android 的内部存储器中移动文件 a? - How to move file a from internal storage of android? 如何从非 AppCompatActivity Class 启动 AppCompatActivity? - How to Start an AppCompatActivity from a non AppCompatActivity Class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM