小编典典

屏幕截图另存为自动生成的文件名

java

我做了一个按钮来截取屏幕截图并保存到Pictures文件夹中。我将其设置为以capture.jpeg的名称保存,但我希望将其保存为cafe001.jpeg,caf002.jpeg这样。还请您告诉我如何将其保存为time
format.jpeg吗?提前谢谢你的帮助

container = (LinearLayout) findViewById(R.id.LinearLayout1);
        Button captureButton = (Button) findViewById(R.id.captureButton);
        captureButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            container.buildDrawingCache();
            Bitmap captureView = container.getDrawingCache();
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "capture.jpeg");
                captureView.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Toast.makeText(getApplicationContext(),
                    "Captured under Pictures drectory", Toast.LENGTH_LONG)
                    .show();
        }
    });

阅读 627

收藏
2020-09-28

共1个答案

小编典典

您基本上有两种选择…

你可以…

列出目录中的所有文件,然后简单地将文件计数增加1并使用…

File[] files = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()).
    listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            String name = pathname.getName();
            return pathname.isFile() && name.toLowerCase().startsWith("capture") && name.toLowerCase().endsWith(".jpeg");
        }
});

int fileCount = files.length();

fos = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + 
    "capture" + fileCount + ".jpeg");

当然,如果存在具有相同索引的文件,则不会考虑…

你可以…

列出所有文件,对其进行排序,获取最后一个文件,找到它的索引值并递增…

就像是…

File[] files = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()).
    listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            String name = pathname.getName();
            return pathname.isFile() && name.toLowerCase().startsWith("capture") && name.toLowerCase().endsWith(".jpeg");
        }
});

Arrays.sort(files);
File last = files[files.length - 1];

Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(last.getName());

int index = 1;
if (matcher.find()) {
    String match = matcher.group();
    index = Integer.parseInt(match) + 1;
}

String fileName = "capture" + index + ".jpeg"

你可以…

只需创建一个循环,直到找到一个空的索引位置即可。

2020-09-28