java File类的基本使用方法
Java IO中File的使用是比较频繁的,在文件的上传和删除中都会用到的。比如我们在写管理系统的时候有可能会用到图片的上传和删除。那么我们就会用到Java的 File来处理。本文是百分网小编搜索整理的关于java File类的基本使用方法,给大家做个参考,希望对大家有所帮助!想了解更多相关信息请持续关注我们应届毕业生考试网!
Java中File的基本使用创建和删除文件:
public class FileDemo {
public static void main(String[] args) {
File f=new File("d:"+File.separator+"io.txt");
/pic/p>
/pic/p>
try {
f.createNewFile();
} catch (IOException e) {
/pic/p>
e.printStackTrace();
}
/pic/p>
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
/pic/p>
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();
/pic/p>
f1.getName();
这是Java IO中的基础使用,也是使用比较频繁的部分。
【java File类的基本使用方法】相关文章:
java中File类的使用方法12-23
java中File类有哪些使用方法10-13
java中File类的使用方法有哪些09-26
Java基础之File类的使用12-06
Java File类有哪些常用方法02-15
Java类的基本构成10-28
Java类的基本构成11-07
Java类的基本构成12-04
Java类基本构成01-22