java File類的根本應用辦法總結。本站提示廣大學習愛好者:(java File類的根本應用辦法總結)文章只能為提供參考,不一定能成為您想要的結果。以下是java File類的根本應用辦法總結正文
Java IO中File的應用是比擬頻仍的,在文件的上傳和刪除中都邑用到的。好比我們在寫治理體系的時刻有能夠會用到圖片的上傳,和刪除。那末我們就會用到Java的 File來處置。
Java中File的根本應用創立和刪除文件:
public class FileDemo {
public static void main(String[] args) {
File f=new File("d:"+File.separator+"io.txt");
//File.separator 獲得“\”
//File.pathSeparator獲得是“;”
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//等等一段時光,可以檢查文件的生成
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(f.exists()){
f.delete();
}else{
System.out.println("文件不存在");
}
}
}
Java File示例應用:在J2EE開辟中應用的圖片上傳功效代碼:
public void fileUpload(@RequestParam MultipartFile[] myfiles,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
String imgPath = "/uploads" + "/";
File directory = new File(request.getSession().getServletContext()
.getRealPath("/")
+ imgPath);
String desFileName = null;
String fileNewName = null;
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String originalFilename = null;
for (MultipartFile myfile : myfiles) {
if (myfile.isEmpty()) {
out.write("請選擇文件後上傳");
out.flush();
} else {
originalFilename = myfile.getOriginalFilename();
if (null != originalFilename && originalFilename.length() > 0) {
fileNewName = UUID.randomUUID() + originalFilename;
desFileName = directory.toString() + "/" + fileNewName;
}
try {
FileUtils.copyInputStreamToFile(myfile.getInputStream(),
new File(desFileName));
} catch (IOException e) {
e.printStackTrace();
out.write("文件上傳掉敗,請重試!!");
out.flush();
}
}
}
out.print(fileNewName);
out.flush();
}
而且個中文件夾生成的代碼以下:
File f1=new File("d:"+File.separator+"test");
f1.mkdir();
//獲得文件夾稱號的辦法
f1.getName();
這是Java IO中的基本應用,也是應用比擬頻仍的部門。
以上就是本文的全體內容,願望對年夜家的進修有所贊助。