4

请参阅以下(两个)答案以获取解决方案。


我似乎无法正确地理解我的逻辑,出于某种原因,这确实让我受益匪浅,但它似乎(并且可能是)如此简单。我想做的是捕捉图像,如果存在,增加数字。即 photo1.jpg 存在,所以将新文件另存为 photo2.jpg 等。

在我运行代码并拍照的那一刻,“photo.jpg”被保存,然后在下一次捕获时,“photo1.jpg”被保存,然后是“photo11.jpg”,然后是“photo111.jpg” “, ETC。

这是我的代码:

        String photoName = "photo.jpg";
        String i = "0";
        int num = 0;

        File photo = new File(Environment.getExternalStorageDirectory(), photoName);

        while(photo.exists()) {             
            //photo.delete();
            num = Integer.parseInt(i);
            num++;
            String concatenatedNum = Integer.toString(num);
            StringBuffer insertNum = new StringBuffer(photoName);
            photoName = insertNum.replace(5, 5, concatenatedNum).toString();
                                //insert

            photo = new File(Environment.getExternalStorageDirectory(), photoName);
        }

        FileOutputStream fostream = null;

        try {
            fostream = new FileOutputStream(photo.getPath());

            //MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle, yourDescription);

            //write jpeg to local drive
            fostream.write(jpeg[0]);
            fostream.close();
        }
        catch (IOException e) { e.printStackTrace(); }
        finally
        {
            if(fostream != null)
            {
                try
                {
                    fostream.flush();
                    fostream.close();
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

任何帮助深表感谢。

谢谢。


我已经实现了以下解决方案,现在无论我捕获多少张图像,我都只会得到 2 个文件。'photo.jpg' 和 'photo1.jpg' 已成功保存,但没有保存其他图像。他们甚至没有被重写。有什么帮助吗?

现在代码如下:

        String photoName = "photo.jpg";
        String i = "0";
        int num = 0;

        File photo = new File(Environment.getExternalStorageDirectory(), photoName);

        while(photo.exists()) {             
            //photo.delete();
            num = Integer.parseInt(i);
            num++;      
            photoName = "photo" + num + ".jpg";
            photo = new File(Environment.getExternalStorageDirectory(), photoName);
            //String concatenatedNum = Integer.toString(num);
            //StringBuffer insertNum = new StringBuffer(photoName); 

            //photoName = insertNum.insert(5, concatenatedNum).toString();

        }
4

2 回答 2

7

用这个替换你的while循环:

   while(photo.exists()) {             
        num++;
        photoName = "photo"+num+".jpg";
        photo = new File(Environment.getExternalStorageDirectory(), photoName);
   }
于 2013-05-26T22:45:28.987 回答
2

对于新的解决方案 - 为什么你有以下行?

num = Integer.parseInt(i);

i 永远不会改变,所以 num 也永远不会改变。看起来代码将无限循环。如果您删除该行,它应该可以工作。

于 2013-05-26T23:21:35.160 回答