【问题标题】:get sd card path in android vs hard coded path在android中获取sd卡路径与硬编码路径
【发布时间】:2016-04-14 12:37:07
【问题描述】:

我的代码工作正常,它将图像下载到 sd 卡,但是,我在定义我的 sd 卡路径时收到此警告“不要硬编码”/sdcard/”;使用 Environment.getExternalStorageDirectory().getPath( ) 而不是"

@Override
    protected String doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/.temp");//.temp is the image file name
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
    }

问题是,如果我使用建议的解决方案,那么我将无法给我下载的文件一个新名称(“.temp”)

【问题讨论】:

  • OutputStream output = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), ".temp").getAbsolutePath())

标签: android


【解决方案1】:

使用文件和目录时,最好使用File 对象而不是字符串。以下是解决警告的方法:

File dir = Environment.getExternalStorageDirectory();
File tmpFile = new File(dir, ".temp");
OutputStream output = new FileOutputStream(tmpFile);

这将创建一个 File 对象,该对象指向环境的外部存储目录中名为 ".temp" 的文件。然后,它使用 FileOutputStream 类的不同构造函数打开它以进行写入。

如果您需要将文件路径作为字符串来代替(例如,用于打印),您也可以这样做:

String tmpFileString = tmpFile.getPath();

或者,如果您决定将来使用java.nio API 并需要Path 对象:

Path tmpFilePath = tmpFile.toPath();

【讨论】:

  • 字符串和路径有什么区别?
  • @abbie - String 就是这样——一段文字。 Path 对象是 java.nio API 的一部分。出于您的目的,File 可能是最好的选择;你可以创建一个FileOutputStream 传递一个File 作为参数,它工作得很好。
  • 我应该替换“OutputStream output = new FileOutputStream("/sdcard/.temp");" with " String tmpFile = new File(dir, ".temp").getPath();"
  • @abbie - 不,请参阅我的编辑。您应该将其替换为OutputStream output = new FileOutputStream(tmpFile);,其中tmpFileFile 对象。
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多