Java对各种文件的操作详解
java中提供了io类库,可以轻松的用java实现对文件的各种操作。下面就来说一下如何用java来实现这些操作。
新建目录<%@ page contentType="text/html;charset=gb2312"%>
<%
//String URL = request.getRequestURI();
String filePath="C:\\测试\\";
filePath=filePath.toString();//中文转换
java.io.File myFilePath=new java.io.File(filePath);
if(!myFilePath.exists())
myFilePath.mkdir();
%>
新建文件
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%
String filePath="c:/测试/newFile.txt";
filePath=filePath.toString();
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile=new FileWriter(myFilePath);
PrintWriter myFile=new PrintWriter(resultFile);
String content ="这是测试数据";
String strContent = content.toString();
myFile.println(strContent);
resultFile.close();
%>
删除文件<%@ page contentType="text/html;charset=gb2312"%>
<%
String filePath="c://测试//newFile.txt";
filePath=filePath.toString();
java.io.File myDelFile=new java.io.File(filePath);
if(myDelFile.exists())
{
myDelFile.delete();
out.println(filePath+"删除成功!!!");
}
else
{
out.println(filePath+"该文件不存在");
}
%>
文件拷贝<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
int bytesum=0;
int byteread=0;
//file:读到流中
InputStream inStream=new FileInputStream("c://测试//newFile.txt");
FileOutputStream fs=new FileOutputStream( "c://测试//copyFile.txt");
byte[] buffer =new byte[1444];
int length;
while ((byteread=inStream.read(buffer))!=-1)
{
out.println("<DT><B>"+byteread+"</B></DT>");
bytesum+=byteread;
out.println(bytesum);
fs.write(buffer,0,byteread);
}
inStream.close();
%>
整个文件夹拷贝
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*" %>
<%String url1="C:/aaa";
String url2="d:/java/";
(new File(url2)).mkdirs();
File[] file=(new File(url1)).listFiles();
for(int i=0;i<file.length;i++){
if(file[i].isFile()){
file[i].toString();
FileInputStream input=new FileInputStream(file[i]);
FileOutputStream output=new FileOutputStream(url2+"/"+(file[i].getName()).toString());
byte[] b=new byte[1024*5];
int len;
while((len=input.read(b))!=-1){
output.write(b,0,len);
}
output.flush();
output.close();
input.close();
}
}
%>
文件下载
<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="java.io.*" %>
<%
String fileName = "newFile.txt".toString();
//读到流中
InputStream inStream=new FileInputStream("c://测试//newFile.txt");
//设置输出的格式
response.reset();
response.setContentType("text/plain");
response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len;
ServletOutputStream outStream = response.getOutputStream();
while((len=inStream.read(b)) >0)
outStream.write(b,0,len);
outStream.flush();
outStream.close();
inStream.close();
%>