简体   繁体   English

写入 SD 卡时 Android csv 文件不可见

[英]Android csv file not visible when writing to SD card

I have been having an issue that others on the site have already.我一直遇到网站上其他人已经遇到的问题。 I have tried those solutions and they did not work for me.我已经尝试过这些解决方案,但它们对我不起作用。

I'm currently developing an app that would create a csv file based on user input.我目前正在开发一个应用程序,可以根据用户输入创建一个 csv 文件。 The file needs to be retrievable by the user when the device is connected to a PC via USB.当设备通过 USB 连接到 PC 时,用户需要可以检索该文件。 The saving code functions work correctly, however the file is not visible on the PC when the device is connected.保存代码功能正常工作,但是当设备连接时该文件在 PC 上不可见。

This is the full saving code snippet of the app:这是应用程序的完整保存代码片段:

    FileWriter fileWriter = null;
    File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File dir = new File(sdCard.getAbsolutePath() + "/appFolder/");
    File dir2 = new File(sdCard.getAbsolutePath() + "/appFolder/appSubFolder/");
    dir.mkdirs();
    dir2.mkdirs();
    fileName = clientName + " " + agentName + ".csv";
    path = sdCard.getAbsolutePath() + "/appFolder/appSubFolder/";
    file = new File(dir2, fileName);

    dir.setReadable(true);
    dir.setWritable(true);
    dir.setExecutable(true);

    dir2.setReadable(true);
    dir2.setWritable(true);
    dir2.setExecutable(true);

    file.setReadable(true);
    file.setWritable(true);
    file.setExecutable(true);

    this.clientName = clientName;
    this.agentName = agentName;
    BufferedWriter bufferedWriter = null;
    try {
        if(!dir.exists()){
            dir.createNewFile();
            Toast.makeText(context,"dir created", Toast.LENGTH_SHORT).show();
        }
        if(!dir2.exists()){
            dir2.createNewFile();
            Toast.makeText(context,"dir2 created", Toast.LENGTH_SHORT).show();
        }
        if (!file.exists() )
        {
            file.createNewFile();
            Toast.makeText(context,"file created", Toast.LENGTH_SHORT).show();
        }
        /*
        fileWriter = new FileWriter(file, true);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(fullOrder);

        fileWriter.flush();
        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
        */

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append(fullOrder);
        outputStreamWriter.close();
        fileOutputStream.close();

        MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null, null);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(dir)));
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(dir2)));
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    } catch (IOException ioEx) {
        Toast.makeText(context, ioEx.toString(), Toast.LENGTH_SHORT).show();
        Log.d("mTag", "msg");
        Log.d("Exception ioEx 1", ioEx.toString());
    } catch (Exception ex) {
        Toast.makeText(context, ex.toString(), Toast.LENGTH_SHORT).show();
        Log.d("mTag", "msg");
        Log.d("Genereic ex saveToFile", ex.toString());
    }

The file is being written to external storage and while I can see that more space is taken up, the file itself is still not visible.文件正在写入外部存储,虽然我可以看到占用了更多空间,但文件本身仍然不可见。

Any help with what might be the problem would be appreciate.任何可能出现问题的帮助将不胜感激。 Thank you!谢谢!

The way you are sending broadcast to MediaScanner but may not work efficiently and is not recommended too.您向 MediaScanner 发送广播但可能无法有效工作的方式,也不推荐使用。

The recommended way is to add the file paths of the files which have been created/updated, like this [in a String type ArrayList]推荐的方法是添加已经创建/更新的文件的文件路径,像这样[在一个String类型的ArrayList中]

ArrayList<String> filesToBeScanned = new ArrayList<String>();
filesToBeScanned.add(item.getFilePath());

Now you need to run scanFile() static method of the MediaScannerConnection class and pass the String array containing the list of all the files which have been created/updated and needs to be media scanned.现在,你需要运行SCANFILE()的MediaScannerConnection类的静态方法,并通过包含所有已创建/更新,需要扫描介质中的文件列表的字符串数组

You can also put a listener to respond when the scanning has been finished for individual files.您还可以在单​​个文件的扫描完成时放置一个侦听器进行响应。

String[] toBeScannedStr = new String[toBeScanned.size()]; String[] toBeScannedStr = new String[toBeScanned.size()]; toBeScannedStr = fileToBeScanned.toArray(toBeScannedStr); toBeScannedStr = fileToBeScanned.toArray(toBeScannedStr);

            MediaScannerConnection.scanFile(getActivity(), toBeScannedStr, null, new OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    System.out.println("SCAN COMPLETED: " + path);

                }
            });

Hope this solves your prob.希望这能解决您的问题。

For internal storage use:对于内部存储使用:

getFilesDir() or getCacheDir() getFilesDir()getCacheDir()

See android documentation:参见安卓文档:
https://developer.android.com/training/data-storage https://developer.android.com/training/data-storage

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

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