【问题标题】:saving file in internal storage android将文件保存在内部存储android中
【发布时间】:2012-10-21 02:51:45
【问题描述】:

我是 android 新手,当我尝试将文件保存到内部存储时遇到问题,新示例适用于我的 sdk,但不适用于我的手机。

我正在尝试在索尼爱立信 xperia 中运行示例,顺便说一下,使用 android 2.1... log.i - 给了我下一行:

/data/data/com.example.key/files/text/(my_title) 

谢谢。

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            setContentView(R.layout.new_text);

            file = (EditText) findViewById(R.id.title_new);
            entry = (EditText) findViewById(R.id.entry_new);

            btn = (Button) findViewById(R.id.save_new);
            btn.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {

                    File myDir = getFilesDir();


                    NEWFILENAME = file.getText().toString();
                    if (NEWFILENAME.contentEquals("")){
                        NEWFILENAME = "UNTITLED";
                    }
                    NEWENTRY = entry.getText().toString();

                    try {

                        File file_new = new File(myDir+"/text/", NEWFILENAME);
                        file_new.createNewFile();

                        Log.i("file", file_new.toString());

                        if (file_new.mkdirs()) {
                            FileOutputStream fos = new FileOutputStream(file_new);

                            fos.write(NEWENTRY.getBytes());
                            fos.flush();
                            fos.close();
                        }

                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Intent textPass = new Intent("com.example.TEXTMENU");
                    startActivity(textPass);
                }
            });

            }


 //That's for creating... then in other activity i'm reading

            @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.text_menu);

            btn = (Button) findViewById(R.id.newNote);
            listfinal = (ListView) findViewById(R.id.listView);

            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent textPass = new Intent("com.example.TEXTNEW");
                    startActivity(textPass);

                }
            });

            listfinal.setOnItemClickListener(this);

            File fileWithinMyDir = getApplicationContext().getFilesDir();


            loadbtn = (Button) findViewById(R.id.loadList);

            loadbtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    File myDir = getFilesDir();

                    File dir = new File(myDir + "/text/");

                    String[] files = dir.list();

                    //String[] files = getApplicationContext().fileList();
                    List<String> list = new ArrayList<String>();

                    for (int i =0; i < files.length; i++){
                        list.add(files[i]);
                    }
                    ArrayAdapter<String> ad = new ArrayAdapter<String>(TextMenu.this,  android.R.layout.simple_list_item_1,
                                    android.R.id.text1, list);

                    listfinal.setAdapter(ad);
                }
            });
            }

在我的 android 清单中我有权限

              <uses-sdk
                    android:minSdkVersion="5"
                    android:targetSdkVersion="15" />

                <uses-permission android:name="android.hardware.camera" />
                <uses-permission android:name="android.permission.INTERNET" />
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

【问题讨论】:

  • 您能提供 LogCat 吗?
  • 尝试使用File.mkdirs()调用创建您要放置文件的目录

标签: android local-storage mkdirs


【解决方案1】:

我不太确定您指的是哪个示例,但我这里有两个工作示例,其中至少一个应该适合您的需要。 我在运行内部版本号 2.1.A.0.435 的 X10、运行内部版本号 7.0.A.1.303 的 Xperia T 和运行内部版本号 JZO54K 的 Nexus S 上测试了这些。

示例 1

    String filename = "myfile";
    String outputString = "Hello world!";

    try {
        FileOutputStream outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(outputString.getBytes());
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        FileInputStream inputStream = openFileInput(filename);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        r.close();
        inputStream.close();
        Log.d("File", "File contents: " + total);
    } catch (Exception e) {
        e.printStackTrace();
    }

示例 2

    String filename = "mysecondfile";
    String outputString = "Hello world!";
    File myDir = getFilesDir();

    try {
        File secondFile = new File(myDir + "/text/", filename);
        if (secondFile.getParentFile().mkdirs()) {
            secondFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(secondFile);

            fos.write(outputString.getBytes());
            fos.flush();
            fos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        File secondInputFile = new File(myDir + "/text/", filename);
        InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
        BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        r.close();
        secondInputStream.close();
        Log.d("File", "File contents: " + total);
    } catch (Exception e) {
        e.printStackTrace();
    }

【讨论】:

  • 为什么支票secondFile.getParentFile().mkdirs()能解释一下吗?
  • 如果您仍然对答案感兴趣:此调用是为了确保文件的路径存在,如果需要,它会创建目录层次结构
  • 如果有人仍然对此答案感兴趣:当针对 API 23+ 时,必须在运行时请求 WRITE_EXTERNAL_STORAGE 权限。否则会出现“Permission denied”错误
  • @LunarWatcher 说得好,你提出来了。我会更新答案,因为它可能会帮助将来来这里的其他人。
【解决方案2】:

即使我在清单文件中授予了读写权限,我也遇到了三星 Galaxy S7 的“权限被拒绝”问题。我通过转到手机设置>>应用程序>> [我的应用程序]解决了这个问题,并在许可下允许“存储”。之后工作正常。

【讨论】:

  • 陷阱:如果应用面向 API 23 或更高版本,则必须在运行时请求写入外部存储权限。 WRITE_EXTERNAL_STORAGE 是一个危险的权限,这意味着它必须被请求。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多