java中提供了io类库,可以轻松的用java实现对文件的各种操作。下面就来说一下如何用java来实现这些操作。
作者:中国IT实验室 来源:中国IT实验室 2007年8月26日
关键字:
文件下载
<%@ 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();
%>
数据库字段中的文件下载
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.util.*,java.sql.*,java.io.*"%>
<%
String id = request.getParameter("id");
if(id==null)
{ throw new Exception ("没有找到图片");
}
else
{
try
{
com.gzrealmap.lib.jdbc.JDBCUtil SqlBean= com.gzrealmap.lib.jdbc.JDBCUtil.getInstance();
SqlBean.connect();
String sql = "select * from innernews where id = '"+79+"'";
ResultSet rs = SqlBean.queryforUpdate(sql);
rs.next();
//String fileNamedb = rs.getString("imageName");
String file= rs.getString("acc");
//String fileName = new String(fileNamedb.getBytes(),"iso-8859-1");
String fileName = "a.jpg";
response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
String filter = fileName.substring(fileName.lastIndexOf("."));
if(filter.equals(".txt"))
{
response.setContentType("text/plain");
}
else if(filter.equals(".doc")||filter.equals(".dot"))
{
response.setContentType("application/msword");
}
else
{
response.setContentType("image/jpeg;charset=GB2312");
}
ServletOutputStream o = response.getOutputStream();
//o.write(file);
out.println(file);
//o.flush();
//o.close();
SqlBean.disconnect();
}
catch(Exception ex)
{
out.println(ex.getMessage());
}
}
%>
把网页保存成文件
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.text.*,java.util.*,java.net.*,java.io.*"%>
<%
URL stdURL = null;
BufferedReader stdIn = null;
PrintWriter stdOut = null;
try {
stdURL = new URL("http://www.163.com");
}
catch (MalformedURLException e) {
throw e;
}
try {
//将字节流转变成为字符流
stdIn = new BufferedReader(new InputStreamReader(stdURL.openStream()));
String theFileName = "c://测试//163.html";
stdOut = new PrintWriter(new BufferedWriter(new FileWriter(theFileName.toString())));
}
catch (IOException e) {
}
/***把URL指定的页面以流的形式读出,写成指定的文件***/
try {
String strHtml = "";
while((strHtml = stdIn.readLine())!=null) {
stdOut.println(strHtml);
}
}
catch (IOException e) {
throw e;
}
finally {
try {
if(stdIn != null)
stdIn.close();
if(stdOut != null)
stdOut.close();
}
catch (Exception e) {
System.out.println(e);
}
}
%>