java - 如何使用 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());
是我遇到错误的地方。我可以使用其他替代方法吗?提前致谢。
解决方案
如果你想从上传的文件创建一个新文件,你可以使用java.io.File类的createTempFile,例如:
*File newFile = File.createTempFile("desiredFileName"+ ":", "extension",
oldFile);*
这里oldFile是上传的文件对象。
推荐阅读
- next.js - 在 Next Auth 中扩展 OAuth 登录的用户数据
- flutter - 带有 CustomScrollView Renderflex 错误的底部导航栏
- amazon-web-services - Aws pinpoint:从 aws 子帐户发送短信
- python - Wit AI 在使用 python API 时得到 500(内部服务器错误)
- python - Tensorflow - 如何修改张量
- python - Python查询以计数获取身高价格用户
- python - 如何将用户的输入转换为文件名?
- javascript - SecurityError: 阻止具有源“ionic://localhost”的框架访问跨域框架。协议、域和端口必须匹配
- robotframework - 无法获取元素的链接定位器
- javascript - 如何将 JavaScript 对象的特定键的值克隆到新变量?