获得Android与硬编码路径的SD卡路径

时间:2016-04-14 03:36:12

标签: android

我的代码工作正常,它将图像下载到SD卡,但是,我得到了这个警告我在哪里定义了我的SD卡路径"不要硬编码" / sdcard /&#34 ;;使用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")

1 个答案:

答案 0 :(得分:0)

使用文件和目录时,最好使用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();
相关问题