首页 > 解决方案 > 如何使用 getBytes()

问题描述

所以我正在尝试创建一个方法,通过它我将上传一个文件。但是在这个方法中创建一个新文件时,我需要使用 getBytes() 方法。但是我收到错误消息。

The method getBytes() is undefined for the type File

我怎样才能克服这个??。下面是我的方法。

public String SomeFile(File file, String basePath, UrlInfoKey urlInfoKey) {
        LOG.info("basePath for back up is {}", basePath);
        String uploadedPath = null;
        String fileDetails = file.getName();
        String locationDetails = fileDetails;
        String locationFolderPath = basePath+"/"+locationDetails;
        File directory = new File(locationFolderPath);
        if(!directory.isDirectory()) {
            LOG.info("creating the directory at {}", locationFolderPath);
            directory.mkdir();
        }
        String filepath = locationFolderPath+"/"+file.getName().trim();
        LOG.info("file path to back up is {}",filepath);
        File creatingFile = new File(filepath);
        try {
            creatingFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(creatingFile);
            fos.write(file.getBytes());
            fos.close();
            uploadedPath = filepath;
        } catch (Exception e) {
            LOG.info("could not create file ", e.getMessage());
        }
        uploadedPath= updateURLWithDBURL(urlInfoKey,uploadedPath);
        LOG.info("file uploaded at location {}",uploadedPath);
        return uploadedPath;
    }
Line:fos.write(file.getBytes());

是我遇到错误的地方。我可以使用其他替代方法吗?提前致谢。

标签: javafile

解决方案


如果你想从上传的文件创建一个新文件,你可以使用java.io.File类的createTempFile,例如:

*File newFile = File.createTempFile("desiredFileName"+ ":", "extension",
                            oldFile);*

这里oldFile是上传的文件对象。


推荐阅读