阿翔编程学-Java文件操作

package com.ocuf.oais.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import com.ocuf.oais.module.FileModule;

/**
 * 文件操作
 *
 * @author CaoXiang
 *
 */
public class FileCommon {
 List<String> list = new ArrayList<String>();

 private static List<String> APPLIST = new ArrayList<String>();

 private static List Mylist = new ArrayList<String>();
 
 private String realPath = this.getClass().getClassLoader().getResource("/").getPath();
 
 public static void main(String[] args) {
  FileCommon f = new FileCommon();
  try {
   //System.out.println(realPath);
   //f.showXml("Archive-Shrink-test.xml");
   f.readFolderByFilePath("E:/workspace/oaisWeb/src/com/ocuf/oais/metadata/file/fileread");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public String xmlDebugForMessage(String filename) throws ParserConfigurationException, SAXException, IOException {
  StringBuffer buffer = new StringBuffer();
  String file = "中国国家税务总局.xml";
  System.out.println(realPath);
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   FileInputStream stream = new FileInputStream(
     realPath+"com//ocuf//oais//metadata//file//filetemp//"+ filename);
   Document document = builder.parse(stream);
   // 获得根节点
   Node root = document.getFirstChild();
   if (root.getTextContent() != null) {
    // System.out.println(root.getTextContent()+" ddd");
    // 获得所有子节点
    NodeList nodeList = root.getChildNodes();
    for(int i=0;i<nodeList.getLength();i++) {
     Node book = nodeList.item(i);
     String title2 = book.getNodeName();
     if(title2.equals("信息总体")) {
      NodeList b2 = nodeList.item(i).getChildNodes();
      for(int ii=0;ii<b2.getLength();ii++) {
       Node book2 = b2.item(ii);
       String title3 = book2.getNodeName();
       if(title3.equals("保护描述信息")) {
        NodeList b3 = b2.item(ii).getChildNodes();
        for(int iii=0;iii<b2.getLength();iii++) {
         Node book3 = b3.item(iii);
         String title4 = book3.getNodeName();
         if(title4.equals("参考信息")) {
          NodeList b4 = b3.item(iii).getChildNodes();
          for(int iiii=0;iiii<b2.getLength();iiii++) {
           Node book4 = b4.item(iiii);
           String title5 = book4.getNodeName();
           if(title5.equals("标识信息")) {
            NodeList list = book4.getChildNodes();
            for(int listsize=0; listsize<list.getLength(); listsize++) {
             buffer.append(list.item(listsize).getTextContent().trim()+",");
            }
           }
          }
         }
        }
       }
      }
     }
    }
    // 关闭流
    stream.close();
   }
   //System.out.println(buffer.toString().substring(1, buffer.toString().length()));
   return buffer.toString().substring(1, buffer.toString().length());
 }

 /**
  * 文件的写入
  *
  * @param filePath(文件路径)
  * @param fileName(文件名)
  * @param args[]
  * @throws IOException
  */

 public void writeFile(String filePath, String fileName, String[] args)
   throws IOException {
  FileWriter fw = new FileWriter(filePath + fileName);
  PrintWriter out = new PrintWriter(fw);
  for (int i = 0; i < args.length; i++) {
   out.write(args[i]);
   out.println();
   out.flush();
  }
  fw.close();
  out.close();
 }

 /**
  *
  * 文件的写入
  *
  * @param filePath(文件路径)
  *
  * @param fileName(文件名)
  *
  * @param args
  *
  * @throws IOException
  *
  */

 public void writeFile(String filePath, String fileName, String args)
   throws IOException

 {

  FileWriter fw = new FileWriter(filePath + fileName);

  fw.write(args);

  fw.close();

 }

 /**
  *
  * 创建与删除文件
  *
  * @param filePath
  *
  * @param fileName
  *
  * @return 创建成功返回true
  *
  * @throws IOException
  *
  */

 public boolean createAndDeleteFile(String filePath, String fileName)
   throws IOException

 {

  boolean result = false;

  File file = new File(filePath, fileName);

  if (file.exists())

  {

   file.delete();

   result = true;

   System.out.println("文件已经删除!");

  }

  else

  {

   file.createNewFile();

   result = true;

   System.out.println("文件已经创建!");

  }

  return result;

 }

 /**
  *
  * 创建和删除目录
  *
  * @param folderName
  *
  * @param filePath
  *
  * @return 删除成功返回true
  *
  */

 public boolean createAndDeleteFolder(String folderName, String filePath)

 {

  boolean result = false;

  try

  {

   File file = new File(filePath + folderName);

   if (file.exists())

   {

    file.delete();

    System.out.println("目录已经存在,已删除!");

    result = true;

   }

   else

   {

    file.mkdir();

    System.out.println("目录不存在,已经建立!");

    result = true;

   }

  }

  catch (Exception ex)

  {

   result = false;

   System.out.println("CreateAndDeleteFolder is error:" + ex);

  }

  return result;

 }

 /**
  *
  * 输出目录中的所有文件及目录名字
  *
  * @param filePath
  *
  */
 public List readFolderByFilePath(String filePath) {
  //System.out.println(realPath);
  this.Mylist.clear();
  File file = new File(filePath);
  File[] tempFile = file.listFiles();
  List backList = new ArrayList();
  //System.out.println(tempFile.length);
  for (int i = 0; i < tempFile.length; i++) {
   if (tempFile[i].isFile()) {
    // System.out.println("File : "+tempFile[i].getName());
   }
   if (tempFile[i].isDirectory()) {
    File file2 = new File(filePath+"/"+tempFile[i].getName());
    //System.out.println("Directory : "+tempFile[i].getName());
    File[] tempFile2 = file2.listFiles();
    for (int j = 0; j < tempFile2.length; j++) {
    if(tempFile2[j].isDirectory()) {
     //System.out.println("Directory : "+tempFile2 [j].getName());
     try {
      //System.out.println(filePath+"/" + tempFile[i].getName() + "/" + tempFile2 [j].getName());
      this.Mylist = this.getFolderByFilePath2(filePath+"/" + tempFile[i].getName() + "/" + tempFile2 [j].getName());
      backList.addAll(this.Mylist);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
    }
   }
  }
  return backList;
 }

 /*
  * (non-Javadoc)
  *
  * @see com.jxsafe.source.common.conf.ISaxReader#getChildNodes(org.w3c.dom.NodeList)
  */
 public List getChildNodes(NodeList childNode) {
  // System.out.println(childNode.getLength());
  for (int i = 0; i < childNode.getLength(); i++) {
   Node obj = (Node) childNode.item(i);
   // System.out.println(obj.getFirstChild().getNodeName());
   // 当该节点没有属性时
   if (!obj.getNodeName().substring(0, 1).equals("#")) {
    // System.out.println(obj.getParentNode().getNodeName());
    if (obj.hasChildNodes()) {
     String title = obj.getFirstChild().getTextContent().trim();
     if (title.equals("") || title == null) {
     } else {
      if (obj.getParentNode().getNodeName().equals("头信息")) {
       // System.out.println(list+" ddd");
       list.add(title);
      } else {
      }
     }
    }
    // 获得该节点的子节点 递归所有的节点
    NodeList childNodes = obj.getChildNodes();
    if (childNodes.getLength() > 0) {
     getChildNodes(childNodes);
    }
   }
  }
  return list;
 }

 /*
  * (non-Javadoc)
  *
  * @see com.jxsafe.source.common.conf.ISaxReader#getChildNodes(org.w3c.dom.NodeList)
  */
 public List getChildNodes2(NodeList childNode) {
  List<String> list = new ArrayList<String>();
  for (int i = 0; i < childNode.getLength(); i++) {
   Node obj = (Node) childNode.item(i);
   // 获得该节点的子节点 递归所有的节点
   NodeList childNodes = obj.getChildNodes();
   if (childNodes.getLength() > 0) {
    for (int j = 0; j < childNodes.getLength(); j++) {
     Node book = childNodes.item(i);
     String title2 = book.getFirstChild().getNodeValue();
     // System.out.println(title2);
     list.add(title2);
    }
   }
  }
  // System.out.println(list);
  return list;
 }

 /*
  * (non-Javadoc)
  *
  * @see com.jxsafe.source.common.conf.ISaxReader#showXml()
  */
 public List showXml(String file) throws Exception {
  list.clear();
  if (file != null) {
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   FileInputStream stream = new FileInputStream(
     realPath+"com//ocuf//oais//metadata//file//filetemp//"
       + file);
   // InputStream stream =
   // this.getClass().getResourceAsStream("E://workspace//oaisWeb//src//com//ocuf//oais//metadata//file//filetemp//"+file);
   // InputStream schemaStr =
   // this.getClass().getResourceAsStream("SubmitInfoPackage.xsd");
   Document document = builder.parse(stream);
   // 获得根节点
   Node root = document.getFirstChild();
   if (root.getTextContent() != null) {
    // System.out.println(root.getTextContent()+" ddd");
    // 获得所有子节点
    NodeList nodeList = root.getChildNodes();
    List v = this.getChildNodes(nodeList);
    // 关闭流
    stream.close();
    // ValidatXML valitate = new ValidatXML();
    // valitate.run(file);
    return v;
   } else {
    return null;
   }
  }
  return new ArrayList();
 }
 
 /*
  * (non-Javadoc)
  *
  * @see com.jxsafe.source.common.conf.ISaxReader#showXml()
  */
 public List showXml2(String filepath, String file) throws Exception {
  list.clear();
  if (file != null) {
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   FileInputStream stream = new FileInputStream(
     filepath + "/"
       + file);
   // InputStream stream =
   // this.getClass().getResourceAsStream("E://workspace//oaisWeb//src//com//ocuf//oais//metadata//file//filetemp//"+file);
   // InputStream schemaStr =
   // this.getClass().getResourceAsStream("SubmitInfoPackage.xsd");
   Document document = builder.parse(stream);
   // 获得根节点
   Node root = document.getFirstChild();
   if (root.getTextContent() != null) {
    // System.out.println(root.getTextContent()+" ddd");
    // 获得所有子节点
    NodeList nodeList = root.getChildNodes();
    List v = this.getChildNodes(nodeList);
    // 关闭流
    stream.close();
    // ValidatXML valitate = new ValidatXML();
    // valitate.run(file);
    return v;
   } else {
    return null;
   }
  }
  return new ArrayList();
 }
 
 /**
  * 获得文件
  *
  * @param filePath
  * @throws Exception
  */
 public List getFolderByFilePath2(String filePath) throws Exception {
  List<FileModule> list = new ArrayList<FileModule>();
  File file = new File(filePath);
  File[] tempFile = file.listFiles();
  for (int i = 0; i < tempFile.length; i++) {
   if (tempFile[i].isFile()) {
    FileModule fileModule = new FileModule();
    // System.out.println(tempFile[i].getName());
    List v = this.showXml2(filePath,tempFile[i].getName());
    // System.out.println(v);
    // System.out.println(tempFile[i].getName()+v.size());
    // 设置相关参数值
    if (v != null) {
     String fname = tempFile[i].getName().substring(0,
       tempFile[i].getName().indexOf("."));
     fileModule.setFileid(String.valueOf(i));
     fileModule.setFilename(fname);
     fileModule.setFilepath(tempFile[i].getPath());
     //取出需要的数据用/分开
     //System.out.println(tempFile[i].getPath());
     //String[] splitArr = tempFile[i].getPath().split("//");
     //System.out.println(tempFile[i].getPath().indexOf("fileread"));
     //System.out.println(tempFile[i].getPath().substring(tempFile[i].getPath().indexOf("fileread")+9, tempFile[i].getPath().length()));
     String newStr = tempFile[i].getPath().substring(tempFile[i].getPath().indexOf("fileread")+9, tempFile[i].getPath().length()).trim().toString();
     int firstIndex = newStr.indexOf("//");
     int lastIndex = newStr.lastIndexOf("//");
     String firstStr = newStr.substring(0, firstIndex);
     String secondStr = newStr.substring(firstIndex+1, lastIndex);
     String totalStr = firstStr+",,,"+secondStr;
     fileModule.setRealpath(totalStr);
     //System.out.println(firstStr+" d " +secondStr);
     // 单位名称
     // String s = v.get(0).toString();
     // System.out.println(s);
     fileModule.setCompanyaddress((String) v.get(0));
     // 单位URI标识
     fileModule.setUri((String) v.get(1));
     // 登陆密码
     fileModule.setPassword((String) v.get(2));
     // 版本号
     fileModule.setVersion((String) v.get(3));
     // 递交时间
     fileModule.setDatetime((String) v.get(4));
     // 紧急程度
     fileModule.setLeavel((String) v.get(5));
     // 类型
     fileModule.setType((String) v.get(6));
     // 密级
     fileModule.setWordcorp((String) v.get(7));
     // IP
     fileModule.setIp((String) v.get(8));
     // 电子签章
     fileModule.setCardnumber((String) v.get(9));
     list.add(fileModule);
    }

   }
  }
  return list;
 }

 /**
  * 获得文件
  *
  * @param filePath
  * @throws Exception
  */
 public List getFolderByFilePath(String filePath) throws Exception {
  List<FileModule> list = new ArrayList<FileModule>();
  File file = new File(filePath);
  File[] tempFile = file.listFiles();
  for (int i = 0; i < tempFile.length; i++) {
   if (tempFile[i].isFile()) {
    FileModule fileModule = new FileModule();
    // System.out.println(tempFile[i].getName());
    List v = this.showXml(tempFile[i].getName());
    // System.out.println(v);
    // System.out.println(tempFile[i].getName()+v.size());
    // 设置相关参数值
    if (v != null) {
     String fname = tempFile[i].getName().substring(0,
       tempFile[i].getName().indexOf("."));
     fileModule.setFileid(String.valueOf(i));
     fileModule.setFilename(fname);
     fileModule.setFilepath(tempFile[i].getPath());
     // 单位名称
     // String s = v.get(0).toString();
     // System.out.println(s);
     fileModule.setCompanyaddress((String) v.get(0));
     // 单位URI标识
     fileModule.setUri((String) v.get(1));
     // 登陆密码
     fileModule.setPassword((String) v.get(2));
     // 版本号
     fileModule.setVersion((String) v.get(3));
     // 递交时间
     fileModule.setDatetime((String) v.get(4));
     // 紧急程度
     fileModule.setLeavel((String) v.get(5));
     // 类型
     fileModule.setType((String) v.get(6));
     // 密级
     fileModule.setWordcorp((String) v.get(7));
     // IP
     fileModule.setIp((String) v.get(8));
     // 电子签章
     fileModule.setCardnumber((String) v.get(9));
     list.add(fileModule);
    }

   }
  }
  return list;
 }
 
 public File[] sortFiles(String filepath) {
  TreeMap   tm=new   TreeMap();  
        File   f=new   File(filepath);  
        File   subFile[]=f.listFiles(); 
        File[] fileArr = new File[subFile.length];
        int   fileNum=subFile.length;  
        for(int   i=0;i<fileNum;i++)  
            {  
                Long   tempLong=new   Long(subFile[i].lastModified());  
                tm.put(tempLong,subFile[i]);  
            }  
      Set   set=tm.keySet();  
      Iterator   iter=set.iterator();  
      int i=0;
      while(iter.hasNext())  
      {  
        Object   key=iter.next();  
        Object   objValue=tm.get(key);  
        File   tempFile=(File)objValue;  
        System.out.println(tempFile.getPath()+"/t"+key.toString()); 
        fileArr[i]=tempFile;
        i++;
      }    
      return fileArr;
 }

 /**
  * 判断文件夹中是否存在文件,没有文件返回错误页
  */
 public boolean countFolderByFilePath(String filePath) {
  File file = new File(filePath);
  File[] tempFile = file.listFiles();
  if (tempFile.length > 0) {
   return true;
  } else {
   return false;
  }
 }

 /**
  *
  * 检查文件中是否为一个空
  *
  * @param filePath
  *
  * @param fileName
  *
  * @return 为空返回true
  *
  * @throws IOException
  *
  */

 public boolean fileIsNull(String filePath, String fileName)
   throws IOException

 {

  boolean result = false;

  FileReader fr = new FileReader(filePath + fileName);

  if (fr.read() == -1)

  {

   result = true;

   System.out.println(fileName + " 文件中没有数据!");

  }

  else

  {

   System.out.println(fileName + " 文件中有数据!");

  }

  fr.close();

  return result;

 }

 /**
  *
  * 读取文件中的所有内容
  *
  * @param filePath
  *
  * @param fileName
  *
  * @throws IOException
  *
  */

 public void readAllFile(String filePath, String fileName)
   throws IOException

 {

  FileReader fr = new FileReader(filePath + fileName);

  int count = fr.read();

  while (count != -1)

  {

   System.out.print((char) count);

   count = fr.read();

   if (count == 13)

   {

    fr.skip(1);

   }

  }

  fr.close();

 }

 /**
  *
  * 一行一行的读取文件中的数据
  *
  * @param filePath
  *
  * @param fileName
  *
  * @throws IOException
  *
  */

 public void readLineFile(String filePath, String fileName)
   throws IOException

 {

  FileReader fr = new FileReader(filePath + fileName);

  BufferedReader br = new BufferedReader(fr);

  String line = br.readLine();

  while (line != null)

  {

   System.out.println(line);

   line = br.readLine();

  }

  br.close();

  fr.close();

 }
 
 /**
  * 字符编码转换
  * @param param
  * @return
  */
 public static String UTF82GB2312(String param)
   {
     try
     {
         new String(param.getBytes("ISO8859-1"), "UTF-8");
         return new String(param.getBytes("ISO8859-1"), "GBK");
     }
     catch(Exception e)
     {
         return null;
     }
   }
 
 /**
  * 字符编码转换
  * @param buf
  * @return
  */
 private static String UTF82GB2312(byte buf[])
   {
     int len = buf.length;
     StringBuffer sb = new StringBuffer(len/2);
     for(int i =0; i<len;i++)
     {
         if(by2int(buf[i])<=0x7F) sb.append((char)buf[i]);
         else if(by2int(buf[i])<=0xDF && by2int(buf[i])>=0xC0)
         {
           int bh = by2int(buf[i] & 0x1F);
           int bl = by2int(buf[++i] & 0x3F);
           bl = by2int(bh << 6 | bl);
           bh = by2int(bh >> 2);
           int c = bh<<8 | bl;
           sb.append((char)c);
         } else if(by2int(buf[i])<=0xEF && by2int(buf[i])>=0xE0){
           int bh = by2int(buf[i] & 0x0F);
           int bl = by2int(buf[++i] & 0x3F);
           int bll = by2int(buf[++i] & 0x3F);
           bh = by2int(bh << 4 | bl>>2);
           bl = by2int(bl << 6 | bll);
           int c = bh<<8 | bl;
     //空格转换为半角
     if(c==58865){
         c = 32;
     }
           sb.append((char)c);
         }
     }
     return sb.toString();
   }

 /**
  * 字符编码转换
  * @param b
  * @return
  */
 private static int by2int(int b)
   {
     return b & 0xff;
   }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值