该方法是先根据指定目录创建文件目录后,再获取起绝对路径,可先在指定目录中放入指定文件,这样就可以直接获取起绝对路径
public static void main(String[] args) {
String filepath = getUploadResource(fileName);
}
public String getUploadResource(String fileName) {
InputStream is = this.getClass().getResourceAsStream("/abc/" + fileName);
String filePath = createFile(fileName);
if (!filePath.contains("EXIST")) {
File file = new File(filePath);
inputStreamToFile(is, file);
return filePath;
}
return filePath.substring(5);
}
public String createFile(String filename) {
String path = System.getProperty("user.dir");
String dirPath = path + File.separator + "abc";
File dir = new File(dirPath);
dir.mkdirs();
String filePath = dirPath + File.separator + filename;
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
return "EXIST" + filePath;
}
public void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)