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中的基础使用,也是使用比较频繁的部分。
以上就是本文的全部内容,希望对大家的学习有所帮助。
本文地址:https://www.stayed.cn/item/14398
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我