您的位置:首页 > 编程语言 > Java开发

Java文件操作大全(2)

2016-07-15 11:26 375 查看
31.文件简单加密

//import java.io.*;

try {

File f=new File((new File(%%1)).getPath()+"\\enc_"+(new File(%%1)).getName().split("//")[1]);

String strFileName = f.getName();

FileInputStream fileInputStream = new FileInputStream(%%2+"\\"+strFilename);

byte[] buffer = new byte[fileInputStream.available()];

FileInputStream.read(buffer);

fileInputStream.close();

for(int i=0;i<buffer.length;i++)

{

int ibt=buffer[i];

ibt+=100;

ibt%=256;

buffer[i]=(byte)ibt;

}

FileOutputStream fileOutputStream = new FileOutputStream(f);

fileOutputStream.write(buffer,0,buffer.length);

fileOutputStream.close();

}

catch(ArrayIndexOutOfBoundException e){

e.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

32.文件简单解密

//import java.io.*;

try {

File f=new File(%%1);

String strFileName = f.getName();

FileInputStream fileInputStream = new FileInputStream(%%2+"\\enc_"+strFilename);

byte[] buffer = new byte[fileInputStream.available()];

FileInputStream.read(buffer);

fileInputStream.close();

for(int i=0;i<buffer.length;i++)

{

int ibt=buffer[i];

ibt-=100;

ibt+=256;

ibt%=256;

buffer[i]=(byte)ibt;

}

FileOutputStream fileOutputStream = new FileOutputStream(f);

fileOutputStream.write(buffer,0,buffer.length);

fileOutputStream.close();

}

catch(ArrayIndexOutOfBoundException e){

e.printStackTrace();

}

catch(IOException e){

e.printStackTrace();

}

33.读取ini文件属性

/*

import java.io.*;

import java.util.*;

import java.util.regex.*;

private static HashMap configMap=null;

private static FileReader fileReader = null;

*/

private static boolean readIni() {

if (configMap == null) {

configMap = new HashMap<String, ArrayList>();

String strLine = null;

String currentNode = null;

String previousNode = null;

ArrayList<Properties>vec = new ArrayList<Properties>();

int row = 0;

BufferedReader bufferedReader = new BufferedReader(fileReader);

try {

while ((strLine = bufferedReader.readLine()) != null) {

String oneLine = strLine.trim();

if (oneLine.length() >= 1) {

Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");

int nodelen = oneLine.split("[;]").length;

String[] strArray1 = new String[4];

if (nodelen == 1) {

oneLine = oneLine.split("[;]")[0].trim();

} else if (nodelen == 2) {

strArray1[3] = oneLine.split("[;]")[1].trim();

oneLine = oneLine.split("[;]")[0].trim();

}

Matcher m = p.matcher(oneLine);

if (m.matches()) {

strArray1[0] = "@Node";

strArray1[1] = oneLine;

strArray1[2] = "";

} else {

int keylen = oneLine.split("=").length;

if (keylen == 1) {

strArray1[0] = "@Key";

strArray1[1] = oneLine.split("=")[0];

strArray1[2] = "";

} else if (keylen == 2) {

strArray1[0] = "@Key";

strArray1[1] = oneLine.split("=")[0];

strArray1[2] = oneLine.split("=")[1];

} else {

strArray1[0] = "@ElementError";

strArray1[1] = "";

strArray1[2] = "";

strArray1[3] = "";

}

}

if (strArray1[0].equals("@Node")) {

previousNode = currentNode;

currentNode = strArray1[1];

if (row > 0) {

configMap.put(previousNode, (ArrayList)vec.clone());

vec.clear();

row = 0;

}

} else if (strArray1[0].equals("@Key") && row == 0) {

Properties ht = new Properties();

ht.setProperty(strArray1[1], strArray1[2]);

vec.add(ht);

row++;

} else if (strArray1[0].equals("@Key") && row > 0) {

Properties ht2 = new Properties();

ht2.put(strArray1[1], strArray1[2]);

vec.add(ht2);

row++;

}

}

}

configMap.put(currentNode, (ArrayList)vec.clone());

} catch (FileNotFoundException e) {

configMap = null;

e.printStackTrace();

return false;

} catch (IOException e) {

configMap = null;

e.printStackTrace();

return false;

}

}

return true;

}

try {

fileReader = new FileReader(%%1); //"Setup.ini"

} catch (FileNotFoundException e1) {

e1.printStackTrace();

}

if (readIni()) {

ArrayList<Properties>li = null;

li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"

for (Properties pro : li) {

if(pro.containsKey(%%3))

%%4=pro.getProperty(%%3);

}

}

try {

fileReader.close();

} catch (IOException e) {

e.printStackTrace();

}

34.合并一个目录下所有的文件

//import java.io.*;

File combinefiles=new File(%%1);

File[] files=combinefiles.listFiles();

FileOutputStream fs;

try {

fs=new FileOutputStream(new File(%%2));

}

catch(IOException e){

e.printStackTrace();

}

for(int i=0;i<files.length;i++){

if(files[i].isFile()){

int bytesum=0;

int byteread=0;

try {

FileInputStream inStream=new FileInputStream(files[i]);

byte[] buffer = new byte[5120];

while((byteread=inStream.read(buffer))!=-1){

bytesum+=byteread;

fs.write(buffer,0,byteread);

}

inStream.close();

}

catch(Exception e){

//复制文件出错

e.printStackTrace();

}

}

}

try {

fs.close();

}

catch(IOException e){

e.printStackTrace();

}

35.写入ini文件属性

/*

import java.io.*;

import java.util.*;

import java.util.regex.*;

private static HashMap configMap=null;

*/

if (readIni()) {

ArrayList<Properties>li = null;

try {

FileWriter fw = new FileWriter("Setup.ini");

li = (ArrayList<Properties>) configMap.get("[DataSource]");

fw.write("[DataSource]\r\n");

for (Properties pro : li) {

if (pro.containsKey("ip"))

fw.write("ip=" + jt1.getText() + "\r\n");

else if (pro.containsKey("username"))

fw.write("username=" + username1 + "\r\n");

else if (pro.containsKey("password"))

fw.write("password=" + password1 + "\r\n");

else if (pro.containsKey("database"))

fw.write("database=" + database1 + "\r\n");

else if (pro.containsKey("table"))

fw.write("table=" + table1 + "\r\n");

}

li = (ArrayList<Properties>) configMap.get("[DataTarget]");

fw.write("\r\n[DataTarget]\r\n");

for (Properties pro : li) {

if (pro.containsKey("ip"))

fw.write("ip=" + jt2.getText() + "\r\n");

else if (pro.containsKey("username"))

fw.write("username=" + username2 + "\r\n");

else if (pro.containsKey("password"))

fw.write("password=" + password2 + "\r\n");

else if (pro.containsKey("database"))

fw.write("database=" + database2 + "\r\n");

else if (pro.containsKey("table"))

fw.write("table=" + table2 + "\r\n");

}

fw.flush();

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

36.获得当前路径

String %%1=this.getClass().getResource("/").getPath();

//String %%1=System.getProperty("user.dir")

37.读取XML数据库

/*

import java.io.*;

import javax.xml.parsers.*;

import org.w3c.dom.*;

private static Document document;

private static Element node;

*/

File xml_file = new File(%%1);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder builder = factory.newDocumentBuilder();

document = builder.parse(xml_file);

} catch (Exception e) {

e.printStackTrace();

}

String subNodeTag = %%2;

Element rootNode = document.getDocumentElement();

//%%2="Product" //%%4="id" //%%6="port"

//%%3="Name" //%%5="001"

NodeList nlist = rootNode.getElementsByTagName(subNodeTag);

int len = nlist.getLength();

for (int i = 0; i < len; i++) {

node = nlist.item(i);

String getNodeAttrValue = null;

NamedNodeMap attrList = node.getAttributes();

for (int j = 0; j < attrList.getLength(); j++) {

if (attrList.item(j).getNodeName().equals(%%4)) {

getNodeAttrValue = attrList.item(j).getNodeValue();

break;

}

}

if (getNodeAttrValue.equals(%%5)) {

nlist = node.getChildNodes();

String %%9=((Element) node).getElementsByTagName(%%3).item(0)

.getFirstChild().getNodeValue();

break;

}

}

38.写入XML数据库

/*

import java.io.*;

import javax.xml.parsers.*;

import org.w3c.dom.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.*;

import javax.xml.transform.stream.*;

private Document document;

private Element node;

*/

File xml_file = new File(%%1);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder builder = factory.newDocumentBuilder();

document = builder.parse(xml_file);

} catch (Exception e) {

e.printStackTrace();

}

String subNodeTag = %%2;

Element rootNode = document.getDocumentElement();

// %%2="Product" //%%4="pid" //%%6="author"

// %%3="Name" //%%5="price"

NodeList nlist = rootNode.getElementsByTagName(subNodeTag);

String ss = null;

int len = nlist.getLength();

for (int i = 0; i < len; i++) {

node = (Element) nlist.item(i);

//node.setAttribute(%%4, "0"+String.valueOf(i)); //ID格式化

String getNodeAttrValue = null;

NamedNodeMap attrList = node.getAttributes();

for (int j = 0; j < attrList.getLength(); j++) {

if (attrList.item(j).getNodeName().equals(%%4)) {

getNodeAttrValue = attrList.item(j).getNodeValue();

break;

}

}

if (getNodeAttrValue.equals("001")) {

nlist = node.getChildNodes();

ss = ((Element) node).getElementsByTagName(%%3).item(0)

.getFirstChild().getNodeValue();

ss = ((Element) node).getElementsByTagName(%%6).item(0)

.getFirstChild().getNodeValue();

ss = ((Element) node).getElementsByTagName(%%5).item(0)

.getFirstChild().getNodeValue();

((Element) node).getElementsByTagName(%%3).item(0)

.getFirstChild().setTextContent(%%7);

((Element) node).getElementsByTagName(%%6).item(0)

.getFirstChild().setTextContent(%%8);

((Element) node).getElementsByTagName(%%5).item(0)

.getFirstChild().setTextContent(%%9);

break;

}

}

if (ss == null) {

node = document.createElement(%%2);

node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1));

node.appendChild(document.createTextNode("\n"));

Element server = document.createElement(%%3);

server.appendChild(document.createTextNode(%%7));

node.appendChild(server);

Element ipNode = document.createElement(%%6);

ipNode.appendChild(document.createTextNode(%%8));

node.appendChild(ipNode);

node.appendChild(document.createTextNode("\n"));

Element port = document.createElement(%%5);

port.appendChild(document.createTextNode(%%9));

node.appendChild(port);

node.appendChild(document.createTextNode("\n"));

rootNode.appendChild(node);

}

TransformerFactory tFactory = TransformerFactory.newInstance();

Transformer transformer = null;

try {

transformer = tFactory.newTransformer();

DOMSource source = new DOMSource(document);

StreamResult result = new StreamResult(xml_file);

transformer.transform(source, result);

} catch (Exception e) {

e.printStackTrace();

}

39.ZIP压缩文件

/*

import java.io.*;

import java.util.zip.*;

*/

//创建文件输入流对象

FileInputStream fis=new FileInputStream(%%1);

//创建文件输出流对象

FileOutputStream fos=new FileOutputStream(%%2);

//创建ZIP数据输出流对象

ZipOutputStream zipOut=new ZipOutputStream(fos);

//创建指向压缩原始文件的入口

ZipEntry entry=new ZipEntry(args[0]);

zipOut.putNextEntry(entry);

//向压缩文件中输出数据

int nNumber;

byte[] buffer=new byte[1024];

while((nNumber=fis.read(buffer))!=-1)

zipOut.write(buffer,0,nNumber);

//关闭创建的流对象

zipOut.close();

fos.close();

fis.close();

}

catch(IOException e)

{

System.out.println(e);

}

40.ZIP解压缩

/*

import java.io.*;

import java.util.zip.*;

*/

try{

//创建文件输入流对象实例

FileInputStream fis=new FileInputStream(%%1);

//创建ZIP压缩格式输入流对象实例

ZipInputStream zipin=new ZipInputStream(fis);

//创建文件输出流对象实例

FileOutputStream fos=new FileOutputStream(%%2);

//获取Entry对象实例

ZipEntry entry=zipin.getNextEntry();

byte[] buffer=new byte[1024];

int nNumber;

while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)

fos.write(buffer,0,nNumber);

//关闭文件流对象

zipin.close();

fos.close();

fis.close();

}

catch(IOException e) {

System.out.println(e);

}

41.获得应用程序完整路径

String %%1=System.getProperty("user.dir");

42.递归删除目录中的文件

/*

import java.io.*;

import java.util.*;

*/

ArrayList<String>folderList = new ArrayList<String>();

folderList.add(%%1);

for (int j = 0; j < folderList.size(); j++) {

File file = new File(folderList.get(j));

File[] files = file.listFiles();

ArrayList<File>fileList = new ArrayList<File>();

for (int i = 0; i < files.length; i++) {

if (files[i].isDirectory()) {

folderList.add(files[i].getPath());

} else {

fileList.add(files[i]);

}

}

for (File f : fileList) {

f.delete();

}

}

43.ZIP压缩文件夹

/*

import java.io.*;

import java.util.*;

import java.util.zip.*;

*/

public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {

ArrayList fileNames = new ArrayList();

ArrayList files = new ArrayList();

FileOutputStream fileOut = null;

ZipOutputStream outputStream = null;

FileInputStream fileIn = null;

StringBuffer sb = new StringBuffer(outputZipNameAndPath);

// FileInputStream fileIn =null;

try {

if (outputZipNameAndPath.indexOf(".zip") != -1) {

outputZipNameAndPath = outputZipNameAndPath;

} else {

sb.append(".zip");

outputZipNameAndPath = sb.toString();

}

fileOut = new FileOutputStream(outputZipNameAndPath);

outputStream = new ZipOutputStream(fileOut);

int outputZipFileNameListSize = 0;

if (outputZipFileNameList != null) {

outputZipFileNameListSize = outputZipFileNameList.size();

}

for (int i = 0; i < outputZipFileNameListSize; i++) {

File rootFile = new File(outputZipFileNameList.get(i).toString());

listFile(rootFile, fileNames, files, "");

}

for (int loop = 0; loop < files.size(); loop++) {

fileIn = new FileInputStream((File) files.get(loop));

outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));

byte[] buffer = new byte[1024];

while (fileIn.read(buffer) != -1) {

outputStream.write(buffer);

}

outputStream.closeEntry();

fileIn.close();

}

return outputZipNameAndPath;

} catch (IOException ioe) {

return null;

} finally {

if (outputStream != null) {

try {

outputStream.close();

} catch (IOException e) {

}

}

if (fileIn != null) {

try {

fileIn.close();

} catch (IOException e) {

}

}

}

}

private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {

if (parentFile.isDirectory()) {

File[] files = parentFile.listFiles();

for (int loop = 0; loop < files.length; loop++) {

listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");

}

} else {

fileList.add(parentFile);

nameList.add(directoryName + parentFile.getName());

}

}

ArrayList outputZipFileName=new ArrayList();

String savePath="";

int argSize = 0;

savePath = %%1;

outputZipFileName.add(%%2);

ZipFileOther instance=new ZipFileOther();

instance.zipFileProcess(outputZipFileName,savePath);

44.验证DTD

/*

import java.io.*;

import javax.xml.parsers.*;

import org.w3c.dom.*;

*/

File xml_dtd = new File(%%1);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder builder = factory.newDocumentBuilder();

document = builder.parse(xml_dtd);

//进行dtd检查

factory.setValidating(true);

} catch (Exception e) {

e.printStackTrace();

}

45.验证Schema

/*

import javax.xml.*;

import javax.xml.transform.stream.*;

import javax.xml.validation.*;

import org.xml.sax.*;

*/

SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

StreamSource ss = new StreamSource(%%1); //"mySchema.xsd"

try {

Schema schema = factory.newSchema(ss);

} catch (SAXException e) {

e.printStackTrace();

}

46.Grep

/*

import java.util.regex.*;

import java.io.*;

*/

throws Exception

Pattern pattern = Pattern.compile(%%1); // 第一个参数为需要匹配的字符串

Matcher matcher = pattern.matcher("");

String file = %%2;

BufferedReader br = null;

String line;

try {

br = new BufferedReader (new FileReader (file)); // 打开文件

} catch (IOException e) {

// 没有打开文件,则产生异常

System.err.println ("Cannot read '" + file

+ "': " + e.getMessage());

}

while ((line = br.readLine()) != null) { // 读入一行,直到文件结束

matcher.reset (line); // 匹配字符串

if (matcher.find()) { // 如果有匹配的字符串,则输出

System.out.println (file + ": " + line);

}

}

br.close(); // 关闭文件

47.直接创建多级目录

//import java.io.*;

File f=new File(%%1);

f.mkdirs();

48.批量重命名

//import java.io.*;

File target = new File("%%1");

String[] files = target.list();

File f = null;

String filename = null;

for (String file : files) {

f = new File(target, file);

filename = f.getName();

if (filename.substring(filename.lastIndexOf(".")).equalsIgnoreCase(

"%%2")) {

f.renameTo(new File(target.getAbsolutePath(), filename.replace(

"%%2", "%%3")));

// 这里可以反复使用replace替换,当然也可以使用正则表达式来替换了 ".txt" ".bat"

}

}

49.文本查找替换

//import java.nio.*;

String s1=%%1;

String s2=%%2;

String s3=%%3;

int pos=%%4;

/*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/

int i,j,k=0;

i = pos;

j = 0;

//将s1转化成StringBuffer型进行操作

repStr = new StringBuffer(s1);

while(i<repStr.length()&&j<s2.length())

{

if(repStr.charAt(i) == s2.charAt(j))

{

++i; ++j;

if(j==s2.length())

{

/*j=s2.length()表示字符串匹配成功,匹配次数加1,此外对主串进行字符串替换*/

k = k+1;

repStr.replace(i-j,i,s3);

//将j进行重新赋值开始新的比较

j = 0;

}

}

else {i = i-j+1; j = 0;}

}

return k;

50.文件关联

//import java.io.*;

try {

Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]"

} catch (IOException e) {

e.printStackTrace();

}

51.操作Excel文件

//http://sourceforge.net/projects/poi/

import java.io.*;

import org.apache.poi.hpsf.*;

import org.apache.poi.poifs.eventfilesystem.*;

static class MyPOIFSReaderListener

     implements POIFSReaderListener

{

public void processPOIFSReaderEvent(POIFSReaderEvent event)

{

SummaryInformation si = null;

try

{

si = (SummaryInformation)

PropertySetFactory.create(event.getStream());

}

catch (Exception ex)

{

throw new RuntimeException

("属性集流\"" + event.getPath() +

event.getName() + "\": " + ex);

}

final String title = si.getTitle();

if (title != null)

System.out.println("标题: \"" + title + "\"");

else

System.out.println("该文档没有标题.");

}

}

String filename = %%1;

POIFSReader r = new POIFSReader();

r.registerListener(new MyPOIFSReaderListener(),

"\005SummaryInformation");

r.read(new FileInputStream(filename));

利用Servlet创建和返回一个工作簿。

package org.apache.poi.hssf.usermodel.examples;

import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

import org.apache.poi.hssf.usermodel.*;

public class HSSFCreate extends HttpServlet {

public void init(ServletConfig config)

   throws ServletException {

super.init(config);

}

public void destroy() {

}

/** 处理HTTP GET 和POST请求

* @param request:请求

* @param response:应答

*/

protected void processRequest(HttpServletRequest request,

HttpServletResponse response)

     throws ServletException, IOException {

response.setContentType("application/vnd.ms-excel");

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet("new sheet");

// 创建一个新的行,添加几个单元格。

// 行号从0开始计算

HSSFRow row = sheet.createRow((short)0);

// 创建一个单元格,设置单元格的值

HSSFCell cell = row.createCell((short)0);

cell.setCellValue(1);

row.createCell((short)1).setCellValue(1.2);

row.createCell((short)2).setCellValue("一个字符串值");

row.createCell((short)3).setCellValue(true);

// 写入输出结果

OutputStream out = response.getOutputStream();

wb.write(out);

out.close();

}

/** 处理HTTP GET请求

* @param request:请求

* @param response:应答

*/

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

     throws ServletException, IOException {

processRequest(request, response);

}

/** 处理HTTP POST请求

* @param request:请求

* @param response:应答

*/

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

     throws ServletException, IOException {

processRequest(request, response);

}

/** 返回关于Servlet的简单说明

*/

public String getServletInfo() {

return "示例:在Servlet中用HSSF创建Excel工作簿";

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: