java中对文件的操作(二)
以前写过一个java中对文件的操作(http://dev.csdn.net/develop/article/19/19064.shtm),但是不全,就把剩下的一些加到评论里边了,但这次改版以后评论里的就看不到了,我就重新贴一下。
10。按行读文件
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
FileReader myFileReader=new FileReader("c:/哈哈.txt");
BufferedReader myBufferedReader=new BufferedReader(myFileReader);
String myString=null;
String resultString=new String();
while((myString=myBufferedReader.readLine())!=null)
{ resultString=resultString+myString+"<br>";
}
out.println(resultString);
myFileReader.close();
%>
11。 数据库里字段文件直接下载到客户端
<%@ page import="java.sql.*"%>
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="DBstep.iDBManager2000.*"%>
<%
String fileName = "bb.doc".toString();
//打开数据库
ResultSet result=null;
String Sql=null;
PreparedStatement prestmt=null;
DBstep.iDBManager2000 DbaObj=new DBstep.iDBManager2000();
DbaObj.OpenConnection();
//取得数据库中的数据
Sql="select * from marklist order by markdate desc";
result=DbaObj.ExecuteQuery(Sql);
result.next();
//将数据库中的数据读到流中
InputStream in =result.getBinaryStream("markbody");
//设置输出的格式
response.reset();
response.setContentType("application/Msword");
response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
//循环取出流中的数据
byte[] b = new byte[1024];
int len;
while((len=in.read(b)) >0)
response.getOutputStream().write(b,0,len);
in.close();
%>
12。文件夹遍历
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
String url1="C:/aaa";
File f=(new File(url1));
if(f.isDirectory()){
File [] fe = f.listFiles();
go_on:
for (int i = 0;i<fe.length;i++){
if (fe[i].isDirectory()){
File [] fe1 = fe[i].listFiles();
for (int j = 0;j<fe1.length;j++){
if (fe1[j].isDirectory())
continue go_on;
out.println(fe1[j].toString());
}
}
else out.println(fe[i].toString());
}
}
%>
13。通过字符编码移动文件
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%
String ret=new String();
try
{
byte[] bytes=new byte[102400];
InputStream in=new FileInputStream("c:/aaa.doc");
in.read(bytes);
ret=new sun.misc.BASE64Encoder().encode(bytes); //具体的编码方法
in.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(java.io.IOException ex)
{
ex.printStackTrace();
}
out.println(ret);
byte[] bytes = new sun.misc.BASE64Decoder().decodeBuffer(ret);
java.io.ByteArrayInputStream inStream=new java.io.ByteArrayInputStream(bytes);
byte[] buffer =new byte[1444];
FileOutputStream fs=new FileOutputStream( "d:/aaa.doc");
int bytesum=0;
int byteread=0;
while ((byteread=inStream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
}
%>
14。把文件编码成base64字符串
<%
String ret=new String();
byte[] bytes=new byte[1024];
String aa="aaaa";
bytes=aa.getBytes();
ret=new sun.misc.BASE64Encoder().encode(bytes); //具体的编码方法
bytes = new sun.misc.BASE64Decoder().decodeBuffer(ret);
aa=new String(bytes);
out.println(aa);
%>