Java中的File.createTempFile获取不兼容的类型错误 [英] File.createTempFile in Java getting Incompatible type error

查看:208
本文介绍了Java中的File.createTempFile获取不兼容的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我在临时目录中创建文件并对其进行处理的地方,我的代码可以正常工作.

Till now my code works fine where I am creating file in temporary directory and processing it.

但是现在我试图提供实际要在其中创建xml文件的特定目录.所以在方法createTmpXmlFile

But now I am trying to provide specific directory where I actually want to create xml file. So in method createTmpXmlFile

    private static Path createTmpXmlFile(final String prefix) {
        try {
            log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
            return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);

        } catch (IOException e) {
            throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
        }
    }

我从

return Files.createTempFile(prefix, XML_SUFFIX);

return File.createTempFile(prefix, XML_SUFFIX, "/tmp/in");

我得到以下错误:

java:不兼容的类型:java.lang.String无法转换为java.io.File.

java: incompatible types: java.lang.String cannot be converted to java.io.File.

如果我在这里更改逻辑,那么它将影响正在调用createTmpXmlFile方法的其他方法.

If I change the logic here then its affecting other method that are calling createTmpXmlFile method.

我真的不明白如何解决此问题.下面是我的代码:

I really don't understand how to resolve this issue. Below is my code:

@Slf4j
public class InputCS implements Runnable {

    public static final String XML_SUFFIX = ".xml";
    
    @Value("${gleifdataimporter.file.dir}")    
    private String gleifZipFile;

    private void processleifZipFile() {
        final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
        isInsideLeiRecord.set(false);
        final StringBuilder currentLeiRecordXml = new StringBuilder();

        try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null)) {
            Path tmpXMLPath = xmlFileFromLeiZipFile(zipFs);

            try (Stream<String> lines = Files.lines(tmpXMLPath)) {
                AtomicInteger processedLinesCounter = new AtomicInteger();
                AtomicInteger currentLineNumber = new AtomicInteger();
                lines.sequential().forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber));
                log.info("{} lines of XML file inside LEIF input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath());
            }catch (IOException e) {
                throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
            } finally {
                Files.delete(tmpXMLPath);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
        }
    }

    private Path xmlFileFromLeiZipFile(FileSystem zipFs) {       //extracts the xml file from zip file
        log.info("Input file {} exists: {}", jobRunner.getInputZipPath(), Files.exists(jobRunner.getInputZipPath()));
        Path tmpXmlPath = createTmpXmlFile("leif__" + System.currentTimeMillis());
        for (Path rootDir : zipFs.getRootDirectories()) {
            try (Stream<Path> files = treeAt(rootDir)) {
                log.info("Trying to extract LEIF XML file from ZIP file into {}.", tmpXmlPath);
                final Path xmlFileInsideZip = files
                        .filter(isNotADir())
                        .filter(Files::isRegularFile)
                        .findFirst()
                        .orElseThrow(() -> new IllegalStateException("No file found in LEI ZIP file."));
                log.info("Path to LEIF XML file inside ZIP file: {}.", xmlFileInsideZip);
                return copyReplacing(xmlFileInsideZip, tmpXmlPath);
            }
        }
        throw new IllegalStateException("No file found in LEI ZIP file " + jobRunner.getInputZipPath() + ".");
    }
    

    private static Path createTmpXmlFile(final String prefix) {
        try {
            log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
            return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);

        } catch (IOException e) {
            throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
        }
    }
    
    @NotNull
    private static Path copyReplacing(Path from, Path to) {
        requireNonNull(from, "Trying to copy from a path, which is null to path " + to + ".");   //trying to copy file where no xml file exist in root directory
        requireNonNull(to, "Trying to copy from path " + from + " to a path, which is null.");
        try {
            return Files.copy(from, to, REPLACE_EXISTING);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot copy from " + from + " to " + to + ". ", e);
        }
    }
    
}

推荐答案

  1. 根据Slaw的建议,使用 Paths.get与Path.of
  1. As suggested by Slaw, use Files#createTempFile(Path,String,String,FileAttribute...) to specify the directory to create temp file.
  2. Use Paths#get(String,String...) for java 7 or 8, or Path#of(String,String...) for java 11 or later to convert String to Path. Further reading: Paths.get vs Path.of


private static Path createTmpXmlFile(final String prefix) {
    try {
        // Java 11 or later
        // return Files.createTempFile(Path.of("/tmp/in"), prefix, XML_SUFFIX);
        // Java 8
        return Files.createTempFile(Paths.get("/tmp/in"), prefix, XML_SUFFIX);
    } catch (IOException e) {
        throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
    }
}

这篇关于Java中的File.createTempFile获取不兼容的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆