Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 保存多个文件,而不替换现有文件_Java_Android - Fatal编程技术网

Java 保存多个文件,而不替换现有文件

Java 保存多个文件,而不替换现有文件,java,android,Java,Android,我试图在一个特定文件夹中保存多个图像第一个图像保存正确,但下一个图像只是替换第一个图像。如何保存多个图像?如何动态命名并使用相同的名称保存图像,但使用不同的扩展名,如image、image1、image2…等 下面是我的代码 public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener{ private static final String TAG = "C

我试图在一个特定文件夹中保存多个图像第一个图像保存正确,但下一个图像只是替换第一个图像。如何保存多个图像?如何动态命名并使用相同的名称保存图像,但使用不同的扩展名,如image、image1、image2…等 下面是我的代码

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);
        }

    }

您可以在
活动中使用计数器变量

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();
}
您应该使用某种持久性存储来存储计数器的当前值,例如
SharedReferences


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

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


要添加时间戳,请参阅:

使用递归调用,可以很容易地实现。下面是代码

/**
 * 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)

如果要累积一组不同的图像,则需要保存到不同的文件名。尝试为每个保存操作自动生成唯一的文件名。