【问题标题】:JAVA Move .JPG and .PDF Files to Specific LocationJAVA 将 .JPG 和 .PDF 文件移动到特定位置
【发布时间】:2017-04-02 15:11:02
【问题描述】:

我想将.pdf 文件和.jpg 文件移动到特定文件夹,然后将特定位置路径保存到数据库。到目前为止,在谷歌的帮助下,我可以将文件复制到新位置(不移动)并将新路径保存到数据库,如下面的代码集所示。

try {
     JFileChooser choose = new JFileChooser();
     choose.showOpenDialog(null);
     File f = choose.getSelectedFile();
     File sourceFile = new File(f.getAbsolutePath());
     File destinationFile = new File("D:\\" + sourceFile.getName());

     FileInputStream fileInputStream = new FileInputStream(sourceFile);
     FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

    int bufferSize;
    byte[] bufffer = new byte[512];
    while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
       fileOutputStream.write(bufffer, 0, bufferSize);
       }

    fileInputStream.close();
    fileOutputStream.close();

 } 
 catch (Exception e){
    e.printStackTrace();
    }

我想知道的是

  1. 如何移动具有唯一名称的文件而不是复制..?
  2. 如何显示该文件是否已成功移动的消息 或不在 JOptionpane 中(因为只有我可以插入 部分)..?
  3. 如何检索那些图像链接以直接打开(如'click 此处打开报告'),它应该在计算机默认打开 图片查看器或 PDF 查看器

请帮助我厌倦了谷歌搜索两个半星期。谢谢大家

【问题讨论】:

    标签: java file file-copying


    【解决方案1】:

    这是一个例子,你可以做什么,你想要什么:

    • choose() 仅限于 PDF 和 JPG
    • move() 文件到目的地
    • open() 与默认程序

    根据您评论中的要求添加:

    • getFileExtension() 获取最后一个点之后的字符串
    • 根据今天的时间戳 + 索引 + 扩展生成目的地路径()

    编辑的类:

        package testingThings;
    
        import java.awt.Desktop;
        import java.io.IOException;
        import java.nio.file.Files;
        import java.nio.file.Path;
        import java.nio.file.Paths;
        import java.text.SimpleDateFormat;
        import java.util.Arrays;
        import java.util.Calendar;
        import java.util.Date;
    
        import javax.swing.JFileChooser;
        import javax.swing.JOptionPane;
        import javax.swing.filechooser.FileNameExtensionFilter;
    
        public class FileHandler {
    
            public Path choose() {
                JFileChooser choose = new JFileChooser();
                choose.setFileFilter(new FileNameExtensionFilter("PDF and JPG", "pdf", "jpg"));
                choose.showOpenDialog(null);
    
                Path sourcePath = choose.getSelectedFile().toPath();
    
                return sourcePath;
            }
    
            public void move(Path sourcePath, Path destinationPath) {
                try {
                    Files.move(
                            sourcePath, 
                            destinationPath//, 
                            // since the destinationPath is unique, do not replace
        //                  StandardCopyOption.REPLACE_EXISTING,
                            // works for moving file on the same drive 
                            //its basically a renaming of path
        //                  StandardCopyOption.ATOMIC_MOVE
                    );
        //          JOptionPane.showMessageDialog(null, "file " + sourcePath.getFileName() + " moved");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    JOptionPane.showMessageDialog(
                            null, 
                            "moving failed for file: " + sourcePath.getFileName(),
                            "Error",
                            JOptionPane.ERROR_MESSAGE
                    );
                    e.printStackTrace();
                    System.exit(1);
                }
            }
    
            public void open(Path destinationPath) {
                try {
                    Desktop.getDesktop().open(destinationPath.toFile());
                } catch (IOException e1) {
                    JOptionPane.showMessageDialog(
                            null, 
                            "file openning fails: " + destinationPath.getFileName(), 
                            "Error",
                            JOptionPane.ERROR_MESSAGE
                    );
                    System.exit(1);
                }
            }
    
            public static void main(String[] args) {
                FileHandler fileHandler = new FileHandler();
                Path sourcePath = fileHandler.choose();
    
                String extension = fileHandler.getFileExtension(sourcePath);
                Path destinationPath = fileHandler.generateDestinationPath(extension);
    
                fileHandler.move(sourcePath, destinationPath);
                fileHandler.open(destinationPath);
            }
    
            /**
            * Generate a path for a file with given extension.
            * The Path ist hardcoded to the folder "D:\\documents\\". The filename is the current date with appended index. For Example: 
            * <ul>
            *   <li>D:\\documents\\2016-11-19__12-13-43__0.pdf</li>
            *   <li>D:\\documents\\2016-11-19__12-13-43__1.pdf</li>
            *   <li>D:\\documents\\2016-11-19__12-13-45__0.jpg</li>
            * </ul>
            * @param extension 
            * @return
            */
            public Path generateDestinationPath(String extension) {
                Date today = Calendar.getInstance().getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd__HH-mm-ss");
    
                String filename;
                Path destinationPath;
                int index = 0;
    
                do {
                    filename = sdf.format(today) + "__" + index + "." + extension;
                    destinationPath = Paths.get("D:\\documents\\" + filename);
                    destinationPath = Paths.get("C:\\Users\\ceo\\AppData\\Local\\Temp\\" + filename);
                    System.out.println(destinationPath);
                    index++;
                }
                while (destinationPath.toFile().exists());
    
                return destinationPath;
            }
    
            /**
            * Return the String after the last dot
            * @param path
            * @return String
            */
            public String getFileExtension(Path path) {
                String[] parts = path.toString().split("\\.");
                System.out.println(path);
                System.out.println(Arrays.toString(parts));
                System.out.println(parts.length);
    
                String extension = parts[parts.length - 1];
                return extension;
            }
        }
    

    【讨论】:

    • 如何给它一个唯一的名字..? (如 img2016-09-13-55.jpg 和 img2016-11-19-20-22.pdf)...?因为操作员上传文件时不必重命名。如果操作员在没有唯一名称的情况下没有上传,他/她可能会替换数据库中已经存在的文档
    • 您的移动文件绑定不起作用,然后我删除了StandardCopyOption.ATOMIC_MOVE 功能。之后它起作用了。为什么会这样..?不删除它我得到一个错误说java.nio.file.AtomicMoveNotSupportedException:
    • @Henry 我在答案中添加了新的文件名生成方法。
    • 原子移动适用于在同一驱动器上移动文件。它基本上是路径的重命名。通过从 D: 复制到 D: 它应该可以工作。从 C: 到 D: 不是。
    • 既然问题已经回答,请点击答案左侧大小的勾号接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2022-12-28
    相关资源
    最近更新 更多