String rootPath =request.getSession().getServletContext().getRealPath("/");//获取工程根目录(在此基础上可指定子目录)
基本语法如下,注意根据绝对路径来读写文件就好。//创建文件 File file = new File(path); if (!file.exists()) { file.createNewFile(); // file.mkdirs(); } //打开文件 PrintStream printStream = new PrintStream(new FileOutputStream(path)); //输入HTML文件内容 stringBuilder.append("<html><head>"); stringBuilder.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); stringBuilder.append("<title>"); stringBuilder.append("</title>"); stringBuilder.append("</head>"); stringBuilder.append("<body>"); stringBuilder.append("<div>"); stringBuilder.append("hello,hello,ML info!")); stringBuilder.append("</div>"); stringBuilder.append("</body></html>"); //将HTML文件内容写入文件中 printStream.println(stringBuilder.toString());
//新建一个文件夹
public void newFolder(String folderPath) {try {
String filePath = folderPath;
File myFilePath = new File(filePath);
if ( ! myFilePath.exists()) {
myFilePath.mkdir();
}
} catch (Exception e) {
System.out.println( " 新建文件夹操作出错 " );
e.printStackTrace();
}
}
// 删除文件夹
public void delFolder(String folderPath){
try {
String filePath = folderPath;
File delPath = new File(filePath);
delPath.delete();
} catch (Exception e) {
System.out.println( " 删除文件夹操作出错 " );
e.printStackTrace();
}
}
// 新建文件
public void createFile(String fileName){
try {
String myFileName = fileName;
if ( ! myFileName.exists()) {
myFileName.createNewFile();
}
} catch (Exception e) {
System.out.println( " 新建文件操作出错 " );
e.printStackTrace();
}
}
// 删除文件
public void delFile(String fileName){
try {
String myFileName = fileName;
myFileName.delete();
} catch (Exception e) {
System.out.println( " 删除文件操作出错 " );
e.printStackTrace();
}
}