java 创建文件与读写

来源:互联网 发布:随心安软件 编辑:程序博客网 时间:2024/06/06 16:59

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());

基本语法如下,注意根据绝对路径来读写文件就好。

//新建一个文件夹

publicvoid 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();
}
}
//删除文件夹
publicvoid delFolder(String folderPath){
try{
String filePath
= folderPath;
File delPath
=new File(filePath);
delPath.delete();
}
catch (Exception e) {
System.out.println(
"删除文件夹操作出错");
e.printStackTrace();
}
}
//新建文件
publicvoid createFile(String fileName){
try{
String myFileName
= fileName;
if (!myFileName.exists()) {
myFileName.createNewFile();
}
}
catch (Exception e) {
System.out.println(
"新建文件操作出错");
e.printStackTrace();
}
}
//删除文件
publicvoid delFile(String fileName){
try{
String myFileName
= fileName;
myFileName.delete();
}
catch (Exception e) {
System.out.println(
"删除文件操作出错");
e.printStackTrace();
}
}

原创粉丝点击