赛迪网 > IT技术 Java > 头条列表
  IT资讯搜索
 
IT产品搜索
[程序开发][网管世界][网络安全][数据库技术]
[操作系统][嘉宾聊天·在线访谈][活动集锦]
[精彩专题][Symantec专区][订阅IT技术周刊]
[开发论坛][网管论坛][安全论坛][数据库论坛]
[操作系统论坛][Sybase专区][IBM dW技术专区]
[病毒求助][病毒与漏洞播报][文档·源码下载]

Java语言对各种文件的操作详解

发布时间:2008.01.03 04:42     来源:赛迪网    作者:lingwen20

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("

"+byteread+"
");
   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  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();
%>
 
数据库字段中的文件下载
<%@ 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);
   }
 }
%>
 
直接下载网上的文件
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%
  int bytesum=0;
  int byteread=0;
  URL url = new URL("http://pimg.163.com/sms/micheal/logo.gif");
  URLConnection conn = url.openConnection();
  InputStream inStream = conn.getInputStream();
 
  /**
  String theFileName = "c:/测试/logo.gif";
  theFileName = theFileName.toString();
  File myFilePath=new File(theFileName);
  if(!myFilePath.exists())
  myFilePath.createNewFile();
  **/
 
  FileOutputStream fs=new FileOutputStream("c:/测试/logo2.gif");
  byte[]  buffer =new  byte[1444];
    while ((byteread=inStream.read(buffer))!=-1)
    {
       out.println("
"+byteread+"
");
       bytesum+=byteread;
       //System.out.println(bytesum);
       fs.write(buffer,0,byteread);
     }
%>
 
按行读文件 <%@ 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+"
";
}
out.println(resultString);
myFileReader.close();
%>
 
对word文档的处理(上传与下载)<%@ page contentType="application/msword" %>

<%
   response.setHeader("Content-disposition","inline; filename=test1.doc"); //线上浏览方式
  // response.setHeader("Content-disposition","attachment; filename=test1.doc");//下载方式
   //以上这行设定传送到前端浏览器时的档名为test1.doc
   //就是靠这一行,让前端浏览器以为接收到一个word档
%>
//然后输出动态内容就可以得到一个word文档了
 
1,打开:
1)文件头上加:<%@ page  contentType="application/msword"%> 
xml文件里:

        doc
        application/msword

2)可以用js,以下代码来自引用:
<%@ page contentType="text/html;charset=gb2312" import= "java.io.*"%>



 
2,下载:
<%@ page contentType="text/html;charset=gb2312" import= "java.io.*"%>
<%// 得到文件名字和路径
  String filename = "jsp.doc";
  String filepath = "C:\\";
 
  // 设置响应头和下载保存的文件名
  response.setContentType("APPLICATION/OCTET-STREAM");
  response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
 
  // 打开指定文件的流信息
  java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
  //FileOutputStream out  = new FileOutputStream(filepath+"测试\\" + filename);
  // 写出流信息
  int i;
  while ((i=fileInputStream.read()) != -1) {
   out.write(i);
  }
  fileInputStream.close();
  out.close();
 %>  
       (责任编辑:包春林)


[ 发表评论 ] 字体[  ] [ 打印 ] [ 进入博客 ] [ 进入论坛 ]  [ 推荐给朋友 ]
  相关文章
· Java入门--新手必读 Java中流的概念 (01-02) · 讨论JAVA操作数据库方式与设计模式应用 (01-02)
· Java入门:对java两个IO基础类的理解 (01-02) · 深入浅析如何在内部类中返回外部类对象 (01-02)
· 高级:编写多线程Java应用程序常见问题 (01-02) · Java入门:初学java的人应该从这里开始 (01-02)
· JAVA基础入门:从.class文件中寻找类名 (01-02) · Java入门:java语言中的一些常用的词汇 (01-02)
· Tomcat5的web应用启动顺序详解 (01-02) · Tomcat类的加载机制 (01-02)
  客户需求反馈表
* 姓  名:
更多资料  了解方案  认识厂商
* 单位名称:
* 联系电话:
* 电子邮件:
  赛迪推荐  
  手机·资费 ·新品·导购·评测·手机资费·宽带
手机搜索  诺基亚 N73 MOTO Z6
  IT产品 ·笔记本·台式机·服务器·打印·投影
IT产品搜索 
  IT技术 ·开发·网管·安全·数据库·操作系统
  信息化 ·热点·专题·访谈·周刊·方案案例
· 整合平台模式多样化 多卡合一模式渐成主流
· 网店征税步入倒计时 电子商务或将重新洗牌
· 谈八大厂商的“云计算”理念 信息化监理
· 企业短信平台解决方案 方正智思系统软件
  IT博客 ·曾剑秋·项立刚·Java学习·网管
  IT技术论坛 ·开发·网管·安全·数据库·系统