- 相關(guān)推薦
java File類的基本使用方法
Java IO中File的使用是比較頻繁的,在文件的上傳和刪除中都會用到的。比如我們在寫管理系統(tǒng)的時候有可能會用到圖片的上傳和刪除。那么我們就會用到Java的 File來處理。本文是百分網(wǎng)小編搜索整理的關(guān)于java File類的基本使用方法,給大家做個參考,希望對大家有所幫助!想了解更多相關(guān)信息請持續(xù)關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!
Java中File的基本使用創(chuàng)建和刪除文件:
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開發(fā)中使用的圖片上傳功能代碼:
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中的基礎(chǔ)使用,也是使用比較頻繁的部分。
【java File類的基本使用方法】相關(guān)文章:
java中File類的使用方法07-21
java中File類有哪些使用方法10-31
Java基礎(chǔ)之File類的使用05-12
Java類的基本構(gòu)成08-28
Java類的基本構(gòu)成09-15
Java類基本構(gòu)成05-11
Java類的基本構(gòu)成09-11
java system類使用方法示例10-09
Java中ArrayList類的使用方法09-30
Java語言Math類的使用方法09-08