保存多个文件而不替换存在的文件

Posted

技术标签:

【中文标题】保存多个文件而不替换存在的文件【英文标题】:Save multiple files without replacing the one that exists 【发布时间】:2016-10-13 23:54:18 【问题描述】:

我正在尝试将多个图像保存在特定文件夹中,第一个图像保存正确,但下一个只是替换了第一个。如何保存多张图片?如何动态命名并保存具有相同名称但具有不同扩展名的图像,如图像、图像1、图像2 ...等 下面是我的代码

public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener
        private static final String TAG = "CameraTest";
        Camera mCamera;
        boolean mPreviewRunning = false;

        @SuppressWarnings("deprecation")
        public void onCreate(Bundle icicle)
            super.onCreate(icicle);
            Log.e(TAG, "onCreate");

            getWindow().setFormat(PixelFormat.TRANSLUCENT);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.cameraview);
            ImageView img = (ImageView) findViewById(R.id.blankImage);

            if(ImageViewActivity.isBlack)
                img.setBackgroundResource(android.R.color.black);
            else
                img.setBackgroundResource(android.R.color.white);

            mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
            mSurfaceView.setOnClickListener(this);
            mSurfaceHolder = mSurfaceView.getHolder();
            mSurfaceHolder.addCallback(this);
            mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState)
            super.onRestoreInstanceState(savedInstanceState);
        
    private void copy(File src, File dst) throws IOException 
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) 
            out.write(buf, 0, len);
        
        in.close();
        out.close();
    
    private File getAlbumStorageDir(Context context, String albumName) 
        // Get the directory for the app's private pictures directory.
        File file = new File(context.getExternalFilesDir(
                Environment.DIRECTORY_PICTURES), albumName);
        if(file.exists())
            return null;
        
        if (!file.mkdirs()) 
            Log.e("MainActivity.error", "Directory not created");
        
        return file;
    

        Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() 

            public void onPictureTaken(byte[] data, Camera camera) 
                // TODO Auto-generated method stub
                if (data != null)
                    //Intent mIntent = new Intent();
                    //mIntent.putExtra("image",imageData);

                    mCamera.stopPreview();
                    mPreviewRunning = false;
                    mCamera.release();
                    Bitmap resizedBitmap=null;
                     try
                         BitmapFactory.Options opts = new BitmapFactory.Options();
                         Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                         bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
                         int width = bitmap.getWidth();
                         int height = bitmap.getHeight();
                         int newWidth = 300;
                         int newHeight = 300;

                         // calculate the scale - in this case = 0.4f
                         float scaleWidth = ((float) newWidth) / width;
                         float scaleHeight = ((float) newHeight) / height;

                         // createa matrix for the manipulation
                         Matrix matrix = new Matrix();
                         // resize the bit map
                         matrix.postScale(scaleWidth, scaleHeight);
                         // rotate the Bitmap
                         matrix.postRotate(90);
                          resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                 width, height, matrix, true);
                         ImageViewActivity.image.setImageBitmap(resizedBitmap);

                     catch(Exception e)
                         e.printStackTrace();
                     
                    //StoreByteImage(mContext, imageData, 50,"ImageName");
                    //setResult(FOTO_MODE, mIntent);
                    FileOutputStream out = null;

                        File picturesDir = getAlbumStorageDir(getBaseContext(), "myDirName");
                    File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic.jpg");
                    try 
                        out = new FileOutputStream(savedPic);
                        resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
                        // PNG is a lossless format, the compression factor (100) is ignored
                     catch (Exception e) 
                        e.printStackTrace();
                     finally 
                        try 
                            if (out != null) 
                                out.close();
                            
                         catch (IOException e) 
                            e.printStackTrace();
                        
                    
                    try 

                        copy(picturesDir, savedPic);
                     catch (IOException e) 
                        Log.e("MainActivity.err", "failed to copy");
                    
                    setResult(585);
                    finish();
                
            
        ;

        protected void onResume()
            Log.e(TAG, "onResume");
            super.onResume();
        

        protected void onSaveInstanceState(Bundle outState)
            super.onSaveInstanceState(outState);
        

        protected void onStop()
            Log.e(TAG, "onStop");
            super.onStop();
        

        @TargetApi(9)
        public void surfaceCreated(SurfaceHolder holder)
            Log.e(TAG, "surfaceCreated");
            mCamera = Camera.open(ImageViewActivity.cameraID);
        

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) 
            Log.e(TAG, "surfaceChanged");

            // XXX stopPreview() will crash if preview is not running
            if (mPreviewRunning)
                mCamera.stopPreview();
            

            Camera.Parameters p = mCamera.getParameters();
            p.setPreviewSize(300, 300);

            if(ImageViewActivity.cameraID == 0)
                String stringFlashMode = p.getFlashMode();
                if (stringFlashMode.equals("torch"))
                        p.setFlashMode("on"); // Light is set off, flash is set to normal 'on' mode
                else
                        p.setFlashMode("torch");
            

            /*mCamera.setParameters(p);*/
            try
                mCamera.setPreviewDisplay(holder);
            catch (Exception e)
                // TODO Auto-generated catch block
                e.printStackTrace();
            
            mCamera.startPreview();
            mPreviewRunning = true;
            mCamera.takePicture(null, mPictureCallback, mPictureCallback);
        

        public void surfaceDestroyed(SurfaceHolder holder) 
            Log.e(TAG, "surfaceDestroyed");
            //mCamera.stopPreview();
            //mPreviewRunning = false;
            //mCamera.release();
        

        private SurfaceView mSurfaceView;
        private SurfaceHolder mSurfaceHolder;

        public void onClick(View v) 
            // TODO Auto-generated method stub
            mCamera.takePicture(null, mPictureCallback, mPictureCallback);
        

    

【问题讨论】:

如果你想积累一堆不同的图像,你需要保存到不同的文件名。尝试为每个保存操作自动生成一个唯一的文件名。 【参考方案1】:

您可以在 Activity 中使用计数器变量:

int counter = 0;

将其附加到您的文件名中,并在成功保存后递增:

File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic" + counter + ".jpg");

try 
    out = new FileOutputStream(savedPic);
    resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored

    counter++; // no exception thrown, increment the counter
 catch (Exception e) 
    e.printStackTrace();

您应该使用某种持久存储来存储计数器的当前值,例如SharedPreferences

或者,您可以使用一些唯一标识符来代替计数器,例如 System.currentTimeMillis,这样您就不必处理跟踪值的问题。

【讨论】:

【参考方案2】:

时间戳设置为 ImageName,这样每次保存时都会使用不同的名称..

添加时间戳参考:here

【讨论】:

【参考方案3】:

使用递归调用,可以轻松实现。下面是代码。

/**
 * fileCount - to avoid overwrite and save file
 * with order ie - test - (1).pdf, test - (2).pdf
 */
fun savePdf(directoryPath: String, fileName: String, fileCount: Int = 0) 

    val newFileName = if (fileCount == 0) 
        "$fileName.pdf"
     else 
        "$fileName - ($fileCount).pdf"
    
    val targetFilePath = File(directoryPath, newFileName)

    if (targetFilePath.exists()) 
        savePdf(directoryPath, fileName, fileCount + 1)
        return
    

    // add your logic to save file in targetFilePath

并在你的代码中这样调用它。

savePdf(directoryPath, fileName)

【讨论】:

以上是关于保存多个文件而不替换存在的文件的主要内容,如果未能解决你的问题,请参考以下文章

在文件夹中存在的多个文件中将日期部分动态替换为当前日期 -15 天

单击“否”替换文件时如何返回保存消息框

python打开一个文件并替换内容[重复]

如何查找多个文件、检查重复文件并用 bash、sed 脚本替换

将文本附加到文本文件而不替换它Python [重复]

合并许多 application.properties 文件而不是在 Spring Boot 上替换?