文件信息封装对象
/**
*
*/
package cross.pauliuyou.io;import java.io.File;
import java.io.IOException;/**
* @author 刘优
*
*/
public abstract class FileInfor
{
public static final int byteNumberPerLine = 10;
public static final int addressStringWidth = 12;
public static final String addressSeperator = " :\t";
public static final String hexValueSeperator = " ;\t";
/**
* 文件对象
*/
protected File file;
/**
* 文件名称
*/
protected String name;
/**
* 文件路径
*/
protected String path;
/**
* 是否是新创建的文件
*/
protected boolean newCreatedFile;
/**
* 文件长度
*/
protected long length;
/**
* 长度描述
*/
protected String lengthString;
/**
* 是否是二进制文件
*/
protected boolean isBinary;
/**
* 文件修改标志
*/
protected boolean modified;
/**
* 文件十六进制模式
*/
protected boolean isHexMode;
/**
* 文件属性描述串
*/
protected String propertyString;
/**
* 文件是否被保存
*/
protected boolean isSaved;
/**
* 文件是否被更改
*/
protected boolean isDirty;
/**
* 用文件名构造对象
* @param fileName 文件名
* @throws IOException
*/
public FileInfor(String fileName) throws IOException
{
this.name = fileName;
this.path = fileName;
}
/**
* 用文件构造对象
* @param file 文件对象
* @throws IOException
*/
public FileInfor(File file) throws IOException
{
this.file = file;
this.name = file.getName();
this.path = file.getAbsolutePath();
}
public File getFile()
{
return file;
}
public String getName()
{
return name;
}
public abstract String getEncode();
public boolean isBinary()
{
return isBinary;
}
public String getPath()
{
return path;
}
public void setModified(boolean modified)
{
this.modified = modified;
}
public boolean isModified()
{
return modified;
}
public String getPropertyString()
{
return propertyString;
}
/**
* @return the isHexMode
*/
public boolean isHexMode()
{
return isHexMode;
} /**
* @param isHexMode the isHexMode to set
*/
public void setHexMode(boolean isHexMode)
{
this.isHexMode = isHexMode;
}
/**
* @return the isSaved
*/
public boolean isSaved()
{
return isSaved;
} public boolean isDirty()
{
return isDirty;
} public void setDirty(boolean isDirty)
{
this.isDirty = isDirty;
}
/**
* @return the length
*/
public long getLength()
{
return length;
} /**
* @return the lengthString
*/
public String getLengthString()
{
return lengthString;
} /**
* @return the newCreatedFile
*/
public boolean isNewCreatedFile()
{
return newCreatedFile;
}
public static String getSpaces(int count)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++)
{
sb.append(' ');
}
return sb.toString();
}
public static String fillZeroForNumber(int number)
{
return fillZeroForNumber(number,addressStringWidth);
}
public static String fillZeroForNumber(int number, int width)
{
return fillZeroForNumber(number + "",width);
}
/**
* @param number
* @param width
* @return
*/
public static String fillZeroForNumber(String numberStr, int width)
{
StringBuffer sb = new StringBuffer();
int fillZeros = width - numberStr.length();
for (int i = 0; i < fillZeros; i++)
{
sb.append("0");
}
return sb.append(numberStr).toString();
}
private static int hexCharToInt(int charInput) throws IOException
{
if (charInput >= '0' && charInput <= '9')
{
charInput -= '0';
}
else if (charInput >= 'A' && charInput <= 'F')
{
charInput = charInput - 'A' + 10;
}
else
{
throw new IOException("十六进制数据 [" + (char)charInput + "] 错误.");
}
return charInput;
}
public static byte hexToByte(String hex) throws IOException
{
hex = hex.toUpperCase();
if (hex.length() == 1)
{
hex = "0" + hex;
}
int value0 = hexCharToInt(hex.charAt(0));
int value1 = hexCharToInt(hex.charAt(1));
return (byte)(value0 << 4 | value1);
}
/**
* @param string
* @throws IOException
*/
public static int hexLineToByteArray(String line,byte[] buf) throws IOException
{
return hexLineToByteArray(line,true,buf);
}
/**
* @param string
* @throws IOException
*/
public static int hexLineToByteArray(String line,boolean normal,byte[] buf) throws IOException
{
if (line == null || line.trim().equals(""))
{
throw new IOException("文件行为为空行");
}
int index1 = line.indexOf(addressSeperator);
int index2 = line.indexOf(hexValueSeperator);
if (index1 == -1)
{
throw new IOException("行数据格式有错误");
}
if (index2 == -1)
{
index2 = line.length();
}
line = line.substring(index1 + addressSeperator.length(),index2).trim();
if (line.length() == 0)
{
if (normal)
{
throw new IOException("每行必须包含" + byteNumberPerLine + "个二进制数据");
}
return 0;
}
String[] byteStrings = line.split("\t");
if (normal && byteStrings.length != byteNumberPerLine)
{
throw new IOException("每行必须包含" + byteNumberPerLine + "个二进制数据");
}
if (buf == null || buf.length < byteNumberPerLine)
{
throw new IOException("输入的缓冲区对象为空或太小");
}
for (int i = 0; i < byteStrings.length; i++)
{
buf[i] = hexToByte(byteStrings[i]);
}
return byteStrings.length;
}
/////////////////////////////////////////////////////////////////////////
public abstract String read() throws IOException;
public abstract String read(String encode) throws IOException;
public abstract void write(String content) throws IOException;
public abstract String getNormalDisplay() throws IOException;
public abstract String getHexDisplay() throws IOException;
public abstract void changeEncode(); public abstract void writeHexByString(String hexString) throws IOException;}
/**
*
*/
package cross.pauliuyou.io;import java.io.File;
import java.io.IOException;/**
* @author 刘优
*
*/
public abstract class FileInfor
{
public static final int byteNumberPerLine = 10;
public static final int addressStringWidth = 12;
public static final String addressSeperator = " :\t";
public static final String hexValueSeperator = " ;\t";
/**
* 文件对象
*/
protected File file;
/**
* 文件名称
*/
protected String name;
/**
* 文件路径
*/
protected String path;
/**
* 是否是新创建的文件
*/
protected boolean newCreatedFile;
/**
* 文件长度
*/
protected long length;
/**
* 长度描述
*/
protected String lengthString;
/**
* 是否是二进制文件
*/
protected boolean isBinary;
/**
* 文件修改标志
*/
protected boolean modified;
/**
* 文件十六进制模式
*/
protected boolean isHexMode;
/**
* 文件属性描述串
*/
protected String propertyString;
/**
* 文件是否被保存
*/
protected boolean isSaved;
/**
* 文件是否被更改
*/
protected boolean isDirty;
/**
* 用文件名构造对象
* @param fileName 文件名
* @throws IOException
*/
public FileInfor(String fileName) throws IOException
{
this.name = fileName;
this.path = fileName;
}
/**
* 用文件构造对象
* @param file 文件对象
* @throws IOException
*/
public FileInfor(File file) throws IOException
{
this.file = file;
this.name = file.getName();
this.path = file.getAbsolutePath();
}
public File getFile()
{
return file;
}
public String getName()
{
return name;
}
public abstract String getEncode();
public boolean isBinary()
{
return isBinary;
}
public String getPath()
{
return path;
}
public void setModified(boolean modified)
{
this.modified = modified;
}
public boolean isModified()
{
return modified;
}
public String getPropertyString()
{
return propertyString;
}
/**
* @return the isHexMode
*/
public boolean isHexMode()
{
return isHexMode;
} /**
* @param isHexMode the isHexMode to set
*/
public void setHexMode(boolean isHexMode)
{
this.isHexMode = isHexMode;
}
/**
* @return the isSaved
*/
public boolean isSaved()
{
return isSaved;
} public boolean isDirty()
{
return isDirty;
} public void setDirty(boolean isDirty)
{
this.isDirty = isDirty;
}
/**
* @return the length
*/
public long getLength()
{
return length;
} /**
* @return the lengthString
*/
public String getLengthString()
{
return lengthString;
} /**
* @return the newCreatedFile
*/
public boolean isNewCreatedFile()
{
return newCreatedFile;
}
public static String getSpaces(int count)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++)
{
sb.append(' ');
}
return sb.toString();
}
public static String fillZeroForNumber(int number)
{
return fillZeroForNumber(number,addressStringWidth);
}
public static String fillZeroForNumber(int number, int width)
{
return fillZeroForNumber(number + "",width);
}
/**
* @param number
* @param width
* @return
*/
public static String fillZeroForNumber(String numberStr, int width)
{
StringBuffer sb = new StringBuffer();
int fillZeros = width - numberStr.length();
for (int i = 0; i < fillZeros; i++)
{
sb.append("0");
}
return sb.append(numberStr).toString();
}
private static int hexCharToInt(int charInput) throws IOException
{
if (charInput >= '0' && charInput <= '9')
{
charInput -= '0';
}
else if (charInput >= 'A' && charInput <= 'F')
{
charInput = charInput - 'A' + 10;
}
else
{
throw new IOException("十六进制数据 [" + (char)charInput + "] 错误.");
}
return charInput;
}
public static byte hexToByte(String hex) throws IOException
{
hex = hex.toUpperCase();
if (hex.length() == 1)
{
hex = "0" + hex;
}
int value0 = hexCharToInt(hex.charAt(0));
int value1 = hexCharToInt(hex.charAt(1));
return (byte)(value0 << 4 | value1);
}
/**
* @param string
* @throws IOException
*/
public static int hexLineToByteArray(String line,byte[] buf) throws IOException
{
return hexLineToByteArray(line,true,buf);
}
/**
* @param string
* @throws IOException
*/
public static int hexLineToByteArray(String line,boolean normal,byte[] buf) throws IOException
{
if (line == null || line.trim().equals(""))
{
throw new IOException("文件行为为空行");
}
int index1 = line.indexOf(addressSeperator);
int index2 = line.indexOf(hexValueSeperator);
if (index1 == -1)
{
throw new IOException("行数据格式有错误");
}
if (index2 == -1)
{
index2 = line.length();
}
line = line.substring(index1 + addressSeperator.length(),index2).trim();
if (line.length() == 0)
{
if (normal)
{
throw new IOException("每行必须包含" + byteNumberPerLine + "个二进制数据");
}
return 0;
}
String[] byteStrings = line.split("\t");
if (normal && byteStrings.length != byteNumberPerLine)
{
throw new IOException("每行必须包含" + byteNumberPerLine + "个二进制数据");
}
if (buf == null || buf.length < byteNumberPerLine)
{
throw new IOException("输入的缓冲区对象为空或太小");
}
for (int i = 0; i < byteStrings.length; i++)
{
buf[i] = hexToByte(byteStrings[i]);
}
return byteStrings.length;
}
/////////////////////////////////////////////////////////////////////////
public abstract String read() throws IOException;
public abstract String read(String encode) throws IOException;
public abstract void write(String content) throws IOException;
public abstract String getNormalDisplay() throws IOException;
public abstract String getHexDisplay() throws IOException;
public abstract void changeEncode(); public abstract void writeHexByString(String hexString) throws IOException;}
package cross.pauliuyou.io;import java.awt.Component;
import java.util.Date;
import java.util.HashMap;import javax.swing.JOptionPane;/**
* 弹出报警窗口.同一标题的窗口只能弹出一次,关闭以后才可以再弹出
* @author 刘优
* @version 1.0
*/
public class MsgBox {
private static HashMap isWindowShowingMap = new HashMap();
public static String msgBoxTitleHead = "";
/**
* 弹出消息窗口
* @param msgBody 消息体
*/
public static void msg(Object msgBody)
{
show(null,msgBody,"消息窗口",1,false);
}
/**
* 弹出消息窗口
* @param msgBody 消息体
*/
public static void msg(Object msgBody,boolean create)
{
show(null,msgBody,"消息窗口",1,false);
}
/**
* 弹出消息窗口
* @param msgBody 消息体
*/
public static void msg(Component parentWindow,String msgBody)
{
show(parentWindow,msgBody,"消息窗口",1,false);
}
/**
* 弹出消息窗口
* @param msgBody 消息体
*/
public static void msg(Component parentWindow,String msgBody,boolean createNew)
{
show(parentWindow,msgBody,"消息窗口",1,createNew);
}
/**
* 弹出消息窗口
* @param msgBody 消息体
* @param title 消息标题
*/
public static void msg(String msgBody,String title)
{
show(null,msgBody,title,1,false);
}
/**
* 弹出消息窗口
* @param msgBody 消息体
* @param title 消息标题
*/
public static void msg(String msgBody,String title,boolean createNew)
{
show(null,msgBody,title,1,createNew);
}
public static void msg(Component parentWindow,String msgBody,String title)
{
show(parentWindow,msgBody,title,1,false);
}
public static void msg(Component parentWindow,String msgBody,String title,boolean createNew)
{
show(parentWindow,msgBody,title,1,createNew);
}
/**
* 弹出警告窗口
* @param msgBody 警告消息
*/
public static void alert(Object msgBody)
{
show(null,msgBody,"警告窗口",2,false);
}
public static void alert(Object msgBody,boolean createNew)
{
show(null,msgBody,"警告窗口",2,createNew);
}
/**
* 弹出警告窗口
* @param msgBody 警告消息
*/
public static void alert(Component parentWindow,String msgBody)
{
show(parentWindow,msgBody,"警告窗口",2,false);
}
public static void alert(Component parentWindow,String msgBody,boolean createNew)
{
show(parentWindow,msgBody,"警告窗口",2,createNew);
}
/**
* 弹出警告窗口
* @param msgBody 警告消息体
* @param title 警告标题
*/
public static void alert(String msgBody,String title)
{
show(null,msgBody,title,2,false);
}
public static void alert(String msgBody,String title,boolean createNew)
{
show(null,msgBody,title,2,createNew);
}
/**
* 弹出警告窗口
* @param msgBody 警告消息体
* @param title 警告标题
*/
public static void alert(Component parentWindow,Object msgBody,String title)
{
show(parentWindow,msgBody,title,2,false);
}
public static void alert(Component parentWindow,Object msgBody,String title,boolean createNew)
{
show(parentWindow,msgBody,title,2,createNew);
}
/**
* 弹出问题窗口
* @param msgBody 问题消息体
*/
public static void question(Object msgBody)
{
show(null,msgBody,"问题窗口",3,false);
}
public static void question(Object msgBody,boolean createNew)
{
show(null,msgBody,"问题窗口",3,createNew);
}
/**
* 弹出问题窗口
* @param msgBody 问题消息体
*/
public static void question(Component parentWindow,String msgBody)
{
show(parentWindow,msgBody,"问题窗口",3,false);
}
public static void question(Component parentWindow,String msgBody,boolean createNew)
{
show(parentWindow,msgBody,"问题窗口",3,createNew);
}
/**
* 弹出问题窗口
* @param msgBody 问题消息体
* @param title 问题标题
*/
public static void question(String msgBody,String title)
{
show(null,msgBody,title,3,false);
}
public static void question(String msgBody,String title,boolean createNew)
{
show(null,msgBody,title,3,createNew);
}
/**
* 弹出问题窗口
* @param msgBody 问题消息体
* @param title 问题标题
*/
public static void question(Component parentWindow,String msgBody,String title)
{
show(parentWindow,msgBody,title,3,false);
}
public static void question(Component parentWindow,String msgBody,String title,boolean createNew)
{
show(parentWindow,msgBody,title,3,createNew);
}
/**
* 弹出错误窗口
* @param msgBody 误消息体
*/
public static void error(Object msgBody)
{
show(null,msgBody,"错误窗口",0,false);
}
public static void error(Object msgBody,boolean createNew)
{
show(null,msgBody,"错误窗口",0,createNew);
}
/**
* 弹出错误窗口
* @param msgBody 误消息体
*/
public static void error(Component parentWindow,String msgBody)
{
show(parentWindow,msgBody,"错误窗口",0,false);
}
public static void error(Component parentWindow,String msgBody,boolean createNew)
{
show(parentWindow,msgBody,"错误窗口",0,createNew);
}
/**
* 弹出错误窗口
* @param msgBody 错误消息体
* @param title 错误标题
*/
public static void error(String msgBody,String title)
{
show(null,msgBody,title,0,false);
}
public static void error(String msgBody,String title,boolean createNew)
{
show(null,msgBody,title,0,createNew);
}
/**
* 弹出错误窗口
* @param msgBody 错误消息体
* @param title 错误标题
*/
public static void error(Component parentWindow,String msgBody,String title)
{
show(parentWindow,msgBody,title,0,false);
}
public static void error(Component parentWindow,String msgBody,String title,boolean createNew)
{
show(parentWindow,msgBody,title,0,createNew);
}
/**
* 弹出提示窗口
* @param msgBody 提示消息体
* @param title 提示标题
* @param windowType 提示窗口类型(3-问题窗口,2-警告窗口,1-消息窗口,0-错误窗口)
*/
public static void show(Component parentWindow,Object msgBody,String title,int windowType,boolean createNew)
{
String titleInfor = msgBoxTitleHead + title;
boolean isShowing = false;
Object obj = isWindowShowingMap.get(titleInfor);
if (obj != null)
{
isShowing = ((Boolean)obj).booleanValue();
}
if (!isShowing || createNew)
{
new ShowBoxThread(parentWindow,msgBody,title,windowType,createNew).start();
}
}
private static class ShowBoxThread extends Thread
{
private Component parentWindow;
private String infor;
private String titleInfor;
private int theType;
private boolean createNew;
public ShowBoxThread(Component parentWindow,Object msgBody,String title,int windowType,boolean createNew)
{
this.parentWindow = parentWindow;
this.infor = msgBody.toString();
this.titleInfor = msgBoxTitleHead + title;
this.theType = windowType;
this.createNew = createNew;
}
public void run()
{
setName("MsgBox<" + titleInfor + ">");
if (!createNew)
{
isWindowShowingMap.put(titleInfor,new Boolean(true));
try
{
JOptionPane.showMessageDialog(parentWindow,new Date() + " > " + infor,titleInfor,theType);
}
catch (Exception e)
{
error("消息窗口的类型参数不正确.(3-问题窗口,2-警告窗口,1-消息窗口,0-错误窗口)");
}
isWindowShowingMap.put(titleInfor,new Boolean(false));
}
else
{
try
{
JOptionPane.showMessageDialog(parentWindow,new Date() + " > " + infor,titleInfor,theType);
}
catch (Exception e)
{
error("消息窗口的类型参数不正确.(3-问题窗口,2-警告窗口,1-消息窗口,0-错误窗口)");
}
}
}
}
public static void main(String [] args)
{
//winMsgBox("test1","title1",1);
msg("test1","title1");
// question("test2");
// question("test2","title2");
// alert("test3");
// alert("test3","title3");
// error("test4");
// error("test4","title4");
//show(null,"test5","title5",4);
}
}
/**
*
*/
package cross.pauliuyou.io;import java.io.File;
import java.io.IOException;/**
* @author Administrator
*
*/
public class EmptyInfor extends FileInfor
{
public EmptyInfor(String fileName) throws IOException
{
super(fileName);
}
/**
* @param file
* @throws IOException
*/
public EmptyInfor(File file) throws IOException
{
super(file);
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#changeEncode()
*/
//@Override
public void changeEncode()
{
// TODO Auto-generated method stub
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#getEncode()
*/
//@Override
public String getEncode()
{
// TODO Auto-generated method stub
return null;
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#getHexDisplay()
*/
//@Override
public String getHexDisplay() throws IOException
{
// TODO Auto-generated method stub
return null;
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#getNormalDisplay()
*/
//@Override
public String getNormalDisplay() throws IOException
{
// TODO Auto-generated method stub
return null;
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#read()
*/
//@Override
public String read() throws IOException
{
// TODO Auto-generated method stub
return null;
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#read(java.lang.String)
*/
//@Override
public String read(String encode) throws IOException
{
// TODO Auto-generated method stub
return null;
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#write(java.lang.String)
*/
//@Override
public void write(String content) throws IOException
{
// TODO Auto-generated method stub
} /* (non-Javadoc)
* @see cross.pauliuyou.io.FileInfor#writeHexByString(java.lang.String)
*/
//@Override
public void writeHexByString(String hexString) throws IOException
{
// TODO Auto-generated method stub
}
}
两部分_1
/**
*
*/
package cross.pauliuyou.io;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.List;
import java.util.Vector;/**
* 普通文件类描述对象
*
* @author 刘优
*
*/
public class NormalFileInfor extends FileInfor
{
/**
* 文件缓冲区
*/
private byte[] fileBuffer;
/**
* 文件编码
*/
private String javaEncode;
/**
* 文件编码,显示用
*/
private String encode;
/**
* 设置为新编码
*/
private String toEncode;
/**
* 文件修改时间
*/
private long modifyTime;
/**
* 文件修改时间描述串
*/
private String modifyTimeString;
/**
* 正常显示的字串
*/
private String normalString;
/**
* 十六进制显示的字串
*/
private String hexString;
/**
* 文件内容的行的集合
*/
private List contentList;
/**
* 用文件名构造对象
* @param fileName 文件名
* @throws IOException
*/
public NormalFileInfor(String fileName) throws IOException
{
this(new File(fileName));
}
/**
* 用文件构造对象
* @param file
* @throws IOException
*/
public NormalFileInfor(File file) throws IOException
{
super(file);
if (file == null || !isFileOk())
{
throw new IOException("File [" + file + "] Not OK");
}
// 如果是已经存在的文件
if (!newCreatedFile)
{
// 读文件内容
readFile();
// 获取文件属性
getFileProperty();
// 如果文件不为空
if (length > 0)
{
// 检测文件的编码方式
checkEncode();
// 检测文件是否为二进制文件
checkBinary();
}
}
}
/**
* 判断文件是否准备好
* @return
*/
private boolean isFileOk()
{
// 文件不存在,则创建新文件
if (!file.exists())
{
try
{
file.createNewFile();
newCreatedFile = true;
}
catch (IOException e)
{
return false;
}
}
// 必须是文件而且可读可写
if (!file.isFile() || !file.canRead() || !file.canWrite())
{
return false;
}
return true;
}
/**
* 取得文件属性
*
*/
private void getFileProperty()
{
length = file.length();
long newValue = 0;
if (length < 1024)
{
lengthString = length + "B";
}
else if (length < (1024 * 1024))
{
newValue = length / 1024;
lengthString = newValue + "KB";
}
else if (length < (1024 * 1024 * 1024))
{
newValue = length / (1024 * 1024);
lengthString = newValue + "MB";
}
else
{
newValue = length / (1024 * 1024 * 1024);
lengthString = newValue + "GB";
}
modifyTime = file.lastModified();
modifyTimeString = new Date(modifyTime).toString();
propertyString = "大小:" + lengthString + "\t";
propertyString += "编码:" + encode + "\t";
propertyString += "时间:" + modifyTimeString;
}
/**
* 读取文件
* @throws IOException
*/
private void readFile() throws IOException
{
FileInputStream fin = new FileInputStream(file);
ByteBuffer buffer = ByteBuffer.allocate(fin.available());
fin.read(buffer.array());
fileBuffer = buffer.array();
}
/**
*
*/
private void checkEncode()
{
encode = "UNKNOWN";
BytesEncodingDetect sinodetector = new BytesEncodingDetect();
try
{
int code = sinodetector.detectEncoding(file);
javaEncode = Encoding.javaname[code];
encode = Encoding.nicename[code];
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* @return
*/
private void checkBinary()
{
if (encode.equals("HZ") || encode.equals("OTHER") || encode.equals("ASCII"))
{
isBinary = false;
for (int j = 0; j < length; j++)
{
byte b = fileBuffer[j];
if (b < 0)
{
continue;
}
if (b < 32 && b != 9 && b != 10 && b != 13)
{
isBinary = true;
encode = "BINARY";
break;
}
}
}
}
/**
* @return the fileBuffer
*/
public byte[] getFileBuffer()
{
return fileBuffer;
} /**
* @return the modifyTime
*/
public long getModifyTime()
{
return modifyTime;
} /**
* @return the modifyTimeString
*/
public String getModifyTimeString()
{
return modifyTimeString;
} /**
* @return the encode
*/
public String getEncode()
{
return encode;
}
/**
* 重新加载文件
* @return
* @throws IOException
*/
public boolean reload() throws IOException
{
if (modified)
{
readFile();
modified = false;
normalString = null;
hexString = null;
return true;
}
return false;
}
/**
* 保存文件缓冲区数据到文件中
* @throws IOException
*/
public void save() throws IOException
{
write(fileBuffer);
}
/**
* 简单读取文件(默认编码)
* @return
* @throws IOException
*/
public String readSimple() throws IOException
{
reload();
return new String(fileBuffer);
}
/**
* 用探测到的编码方式读取文件
*/
public String read() throws IOException
{
return getNormalDisplay();
}
/**
* 用指定的编码方式读取文件
*
*/
public String read(String encode) throws IOException
{
if (this.encode.equals(encode))
{
return read();
}
toEncode = encode;
BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
StringBuffer sb = new StringBuffer();
while (true)
{
String line = fileReader.readLine();
if (line == null)
{
break;
}
sb.append(line).append("\n");
}
return sb.toString();
}
/**
* 用默认的编码来读取文本文件,保存到集合中
* @return
* @throws IOException
*/
public List readToListSimple() throws IOException
{
if (reload() || contentList == null)
{
BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
contentList = new Vector();
while (true)
{
String line = fileReader.readLine();
if (line == null)
{
break;
}
contentList.add(line);
}
}
return contentList;
}
两部分_2
/**
* 用探测到的编码来读取文本文件,保存到集合中
* @return
* @throws IOException
*/
public List readToList() throws IOException
{
BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
List content = new Vector();
while (true)
{
String line = fileReader.readLine();
if (line == null)
{
break;
}
content.add(line);
}
return content;
}
/**
* 用指定的编码来读取文本文件,保存到集合中
* @param encode 指定编码
* @return
* @throws IOException
*/
public List readToList(String encode) throws IOException
{
toEncode = encode;
BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
List content = new Vector();
while (true)
{
String line = fileReader.readLine();
if (line == null)
{
break;
}
content.add(line);
}
return content;
}
/**
* 用默认的编码方式写文件
* @param newContent
* @throws IOException
*/
public void writeSimple(String newContent) throws IOException
{
write(newContent.getBytes());
}
/**
* 用默认的编码方式写文件
* @param newContent
* @throws IOException
*/
public void writeListSimple(List newContent) throws IOException
{
PrintWriter fileWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file)));
for (int i = 0; i < newContent.size(); i++)
{
fileWriter.println(newContent.get(i));
}
fileWriter.close();
}
/**
* 用探测到的编码方式写文本文件
* @param newContent
* @throws IOException
*/
public void writeList(List newContent) throws IOException
{
PrintWriter fileWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),encode));
for (int i = 0; i < newContent.size(); i++)
{
fileWriter.println(newContent.get(i));
}
fileWriter.close();
}
/**
* 用指定的编码方式写文本文件
* @param newContent
* @param newEncode
* @throws IOException
*/
public void writeList(List newContent,String newEncode) throws IOException
{
javaEncode = newEncode;
encode = newEncode;
PrintWriter fileWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),encode));
for (int i = 0; i < newContent.size(); i++)
{
fileWriter.println(newContent.get(i));
}
fileWriter.close();
}
/**
* 用探测到的编码方式写文本文件
*/
public void write(String newContent) throws IOException
{
writeText(newContent,javaEncode);
}
/**
* 用指定的编码方式写文本文件
* @param newContent
* @param newEncode
* @throws IOException
*/
public void write(String newContent,String newEncode) throws IOException
{
javaEncode = newEncode;
encode = newEncode;
writeText(newContent,newEncode);
}
/**
* 用指定的编码方式写文本文件
* @param bytes
* @param newEncode
*/
private void writeText(String text, String newEncode) throws IOException
{
PrintWriter textWriter = null;
if (newEncode != null)
{
textWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),newEncode));
}
else
{
textWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file)));
}
textWriter.print(text);
textWriter.close();
modified = true;
isSaved = true;
}
/**
* 把指定的缓冲区数据写到文件中, 文件原来的内容将丢失
* @param newBuf
* @throws IOException
*/
public void write(byte[] newBuf) throws IOException
{
write(newBuf,0,newBuf.length);
}
/**
* 把指定的缓冲区的数据写到文件中
* @param newBuf
* @param offset
* @param length
* @throws IOException
*/
public void write(byte[] newBuf,int offset,int length) throws IOException
{
FileOutputStream fout = new FileOutputStream(file);
fout.write(newBuf,offset,length);
fout.close();
modified = true;
isSaved = true;
}
/**
* 取得文件的正常显示字串
*/
public String getNormalDisplay() throws IOException
{
if (reload() || normalString == null)
{
if (javaEncode != null)
{
normalString = new String(fileBuffer,javaEncode);
}
else
{
normalString = new String(fileBuffer);
}
}
isHexMode = false;
return normalString;
}
/**
* 取得文件的十六进制显示字串
*/
public String getHexDisplay() throws IOException
{
if (reload() || hexString == null)
{
getHexString();
}
isHexMode = true;
return hexString;
}
private static char [] hexCharArray = {'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
public static String byteToHexString(byte data)
{
int high = (data & 0xF0) >> 4;
int low = data & 0x0F;
return hexCharArray[high] + "" + hexCharArray[low];
}
/**
* 取得文件的十六进制串
*/
private void getHexString()
{
StringBuffer sb = new StringBuffer();
int lineNumber = 0;
sb.append(fillZeroForNumber(lineNumber++ * byteNumberPerLine) + addressSeperator);
StringBuffer chars = new StringBuffer();
for (int j = 0; j < fileBuffer.length; j++)
{
byte b = fileBuffer[j];
sb.append(byteToHexString(b)).append("\t");
if ((char)b == '\n')
{
chars.append("\\n");
}
else
{
chars.append((char)b);
}
if (j % byteNumberPerLine == byteNumberPerLine - 1)
{
sb.append(hexValueSeperator + chars);
sb.append("\n");
sb.append(fillZeroForNumber(lineNumber++ * byteNumberPerLine) + addressSeperator);
chars.delete(0,chars.length());
}
}
hexString = sb.toString();
}
/**
* 更改文件编码方式
* @see cross.pauliuyou.io.FileInfor#changeEncode()
*/
//@Override
public void changeEncode()
{
if (encode.equals("BINARY"))
{
return;
}
javaEncode = toEncode;
toEncode = null;
for (int i = 0; i < Encoding.javaname.length; i++)
{
if (javaEncode.equals(Encoding.javaname[i]))
{
encode = Encoding.nicename[i];
break;
}
}
getFileProperty();
} /** 取得文件属性描述字串
* @see cross.pauliuyou.io.FileInfor#getPropertyString()
*/
//@Override
public String getPropertyString()
{
getFileProperty();
return propertyString;
}
/**
* 把十六进制文本转换为十六进制数据写到文件中
* @see cross.pauliuyou.io.FileInfor#writeHexByString(java.lang.String)
*/
//@Override
public void writeHexByString(String hexString) throws IOException
{
if (hexString == null || hexString.trim().equals(""))
{
return;
}
String [] lines = hexString.trim().split("\n");
byte[] tmp = new byte[byteNumberPerLine];
byte[] buf = new byte[lines.length * 10];
int offset = 0;
for (int i = 0; i < lines.length - 1; i++)
{
hexLineToByteArray(lines[i].trim(),true,tmp);
for (int j = 0; j < byteNumberPerLine; j++)
{
buf[j + offset] = tmp[j];
}
offset += byteNumberPerLine;
}
String lastLine = lines[lines.length - 1].trim();
int realCount = hexLineToByteArray(lastLine,false,tmp);
if (realCount > 0)
{
for (int j = 0; j < realCount; j++)
{
buf[j + offset++] = tmp[j];
}
}
write(buf,0,offset);
}}
/**
*
*/
package cross.pauliuyou.io;import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Vector;import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;/**
* 文件编辑器
*
* @author 刘优
* @version 1.0
*
*/
public class FileEditor extends JFrame implements ActionListener,
MouseListener, KeyListener, ChangeListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String previousOpenDirectory = "FileEditor_PreviousOpenedDirectory";
private static final String previousOpenedFiles = "FileEditor_PreviousOpenedFiles";
private static final String historyListFileName = "FileEditor_HistoryList";
private static NormalFileInfor previousOpenDirectoryInfor;
private static NormalFileInfor previousOpenedFilesInfor;
private static NormalFileInfor historyListFileNameInfor;
static
{
try
{
previousOpenDirectoryInfor = new NormalFileInfor(
previousOpenDirectory);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
previousOpenedFilesInfor = new NormalFileInfor(previousOpenedFiles);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
historyListFileNameInfor = new NormalFileInfor(historyListFileName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public boolean isStandAloneProcess = false;
private int histroyListCount = 20;
private Vector fileInfors = new Vector();
/**
* 可切换画面控件
*/
private JTabbedPane tabbedPane = new JTabbedPane();
private int newFileCount;
private Vector allTextAreas = new Vector();
private Vector allTextPanels = new Vector();
private Vector allFilePropertyTextFields = new Vector();
private Dimension screenDimension;
private String closeFileCommandHead = "closefile_";
private JPopupMenu showFileOperationPopMenu;
private JMenuItem closeFileMenuItem;
private String previousPath = null;
private JRadioButtonMenuItem normalMenuItem = new JRadioButtonMenuItem();
private JRadioButtonMenuItem hexMenuItem = new JRadioButtonMenuItem();
private int tabSize = 8;
private JRadioButtonMenuItem[] encodeMenuItems;
private int encodeTypeCount;
private static final String titleHead = "文件编辑器 - ";
private int currentIndex;
private FileInfor currentFileInfor;
private JTextArea currentTextArea;
private JPanel currentTextPanel;
private JTextField currentPropertyText;
private JMenuItem defaultFileEncodeMenuItem;
private JMenuItem setFileEncodeMenuItem;
private JMenu historyMenu;
private boolean isFrameInited;
private byte[] tempBuf = new byte[100];
public FileEditor()
{
addEmptyNewFile();
thisFrameInit();
}
public FileEditor(String fileName)
{
if (fileName == null)
{
addEmptyNewFile();
}
else
{
String[] fileNames = fileName.split(",");
File[] theFiles = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i++)
{
theFiles[i] = new File(fileNames[i]);
}
setFiles(theFiles);
}
thisFrameInit();
}
public FileEditor(String[] fileNames)
{
setFileNames(fileNames);
thisFrameInit();
}
public FileEditor(File file)
{
this(new File[]
{ file });
}
public FileEditor(File[] files)
{
setFiles(files);
thisFrameInit();
}
/**
*
*/
private File[] confirmFilesToOpen()
{
String openFileDialogBeginPath = null;
if (currentIndex != -1 && currentFileInfor instanceof NormalFileInfor)
{
openFileDialogBeginPath = ((NormalFileInfor) currentFileInfor)
.getFile().getParentFile().getAbsolutePath();
}
else
{
if (previousPath == null)
{
try
{
previousPath = previousOpenDirectoryInfor.readSimple();
}
catch (Exception ex)
{
previousPath = ".";
}
}
openFileDialogBeginPath = previousPath;
}
JFileChooser fileChooser = new JFileChooser(openFileDialogBeginPath);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int rs = fileChooser.showOpenDialog(this);
if (rs == 0)
{
File[] theFiles = fileChooser.getSelectedFiles();
if (theFiles != null && theFiles.length > 0)
{
String thisPath = theFiles[0].getParent();
if (!thisPath.equals(previousPath))
{
previousPath = thisPath;
try
{
previousOpenDirectoryInfor.writeSimple(previousPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return theFiles;
}
return null;
}
private File confirmFilesToSave()
{
String openFileDialogBeginPath = null;
if (currentIndex != -1 && currentFileInfor instanceof NormalFileInfor)
{
openFileDialogBeginPath = ((NormalFileInfor) currentFileInfor)
.getFile().getParentFile().getAbsolutePath();
}
else
{
if (previousPath == null)
{
try
{
previousPath = previousOpenDirectoryInfor.readSimple();
}
catch (IOException ex)
{
previousPath = ".";
}
}
openFileDialogBeginPath = previousPath;
}
JFileChooser fileChooser = new JFileChooser(openFileDialogBeginPath);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setSelectedFile(new File(openFileDialogBeginPath,
currentFileInfor.getName()));
int rs = fileChooser.showSaveDialog(this);
if (rs == 0)
{
File theFile = fileChooser.getSelectedFile();
if (theFile != null)
{
String thisPath = theFile.getParent();
if (!thisPath.equals(previousPath))
{
previousPath = thisPath;
try
{
previousOpenDirectoryInfor.writeSimple(previousPath);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return theFile;
}
else
{
return null;
}
}
class FileEditor - 2
/**
* @param fileNames
*/
private void setFileNames(String[] fileNames)
{
File[] theFiles = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i++)
{
theFiles[i] = new File(fileNames[i]);
}
setFiles(theFiles);
}
/**
* @param files2
* @throws
*/
private void setFiles(File[] theFiles)
{
if (theFiles == null || theFiles.length == 0)
{
addEmptyNewFile();
}
else
{
for (int i = 0; i < theFiles.length; i++)
{
addFile(theFiles[i]);
}
}
}
/**
*
*/
private void addEmptyNewFile()
{
if (!isFrameInited)
{
boolean hasPrevious = true;
try
{
if (previousOpenedFilesInfor.getLength() == 0)
{
hasPrevious = false;
}
else
{
List openedFiles = previousOpenedFilesInfor.readToListSimple();
if (openedFiles == null || openedFiles.size() == 0)
{
hasPrevious = false;
}
else
{
File[] theFiles = new File[openedFiles.size()];
for (int i = 0; i < openedFiles.size(); i++)
{
theFiles[i] = new File(openedFiles.get(i).toString());
}
setFiles(theFiles);
}
}
}
catch (IOException e1)
{
hasPrevious = false;
}
if (hasPrevious)
{
return;
}
}
String content = "";
allTextPanels.add(createFileAreaPanel(content, null));
String newFileName = "新文件" + (++newFileCount);
tabbedPane.add(newFileName, (JPanel)allTextPanels.get(allTextPanels.size() - 1));
try
{
fileInfors.add(new EmptyInfor(newFileName));
setTabbedPaneToLast();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void addFile(File file)
{
int index = -1;
for (int i = 0; i < fileInfors.size(); i++)
{
if (((FileInfor)fileInfors.get(i)).getPath().equals(file.getAbsolutePath()))
{
index = i;
break;
}
}
if (index != -1)
{
setTabbedPane(index);
return;
}
String infors = "";
try
{
NormalFileInfor infor = new NormalFileInfor(file);
if (!isFrameInited && infor.isNewCreatedFile())
{
MsgBox.msg(this, "文件 [" + infor.getPath() + "] 已经被删除");
return;
}
fileInfors.add(infor);
String fileContent = null;
if (infor.isBinary())
{
fileContent = infor.getHexDisplay();
}
else
{
fileContent = infor.getNormalDisplay();
}
String fileDetail = infor.getPropertyString();
tabbedPane.add(file.getName(), createFileAreaPanel(fileContent,
fileDetail));
setTabbedPaneToLast();
addFileNameToHistoryListHead(infor.getPath());
}
catch (IOException e1)
{
infors += e1.toString() + "\n";
MsgBox.error(this, infors);
}
}
private void addFileNameToHistoryListHead(String filePath)
throws IOException
{
if (!new File(filePath).exists())
{
return;
}
List histroyFileNames = null;
try
{
histroyFileNames = historyListFileNameInfor.readToListSimple();
}
catch (Exception ex)
{
}
if (histroyFileNames == null)
{
histroyFileNames = new Vector();
}
while (true)
{
boolean hasEmpty = false;
for (int i = 0; i < histroyFileNames.size(); i++)
{
if (!new File(histroyFileNames.get(i).toString()).exists())
{
hasEmpty = true;
histroyFileNames.remove(i);
break;
}
}
if (!hasEmpty)
{
break;
}
}
if (histroyFileNames.contains(filePath))
{
histroyFileNames.remove(filePath);
}
if (histroyFileNames.size() > histroyListCount)
{
histroyFileNames.remove(histroyFileNames.size() - 1);
}
histroyFileNames.add(0, filePath);
historyListFileNameInfor.writeListSimple(histroyFileNames);
}
/**
*
*/
private void setTabbedPaneToLast()
{
int lastIndex = fileInfors.size() - 1;
setTabbedPane(lastIndex);
}
/**
* @param index
*/
private void setTabbedPane(int index)
{
currentIndex = index;
if (index < 0 || index >= fileInfors.size())
{
// MsgBox.alert(this,"索引 [" + index + "] 超出范围,请检查");
setTitle(titleHead);
return;
}
tabbedPane.setSelectedIndex(index);
currentFileInfor = (FileInfor)fileInfors.get(currentIndex);
currentTextArea = (JTextArea)allTextAreas.get(currentIndex);
currentTextPanel = (JPanel)allTextPanels.get(currentIndex);
currentTextPanel.getAutoscrolls();
currentPropertyText = (JTextField)allFilePropertyTextFields.get(currentIndex);
setTitle(titleHead + "[" + currentFileInfor.getPath() + "]");
currentTextArea.setCaretPosition(0);
if (currentFileInfor.isHexMode())
{
hexMenuItem.setSelected(true);
}
else
{
normalMenuItem.setSelected(true);
}
fixFileEncodeMenus();
}
/**
*
*/
private void fixFileEncodeMenus()
{
if (encodeMenuItems == null)
{
return;
}
String theEncode = currentFileInfor.getEncode();
if (theEncode == null || currentFileInfor instanceof EmptyInfor)
{
encodeMenuItems[Encoding.UTF8].setSelected(true);
return;
}
if ("BINARY".equals(theEncode))
{
encodeMenuItems[encodeTypeCount - 1].setSelected(true);
return;
}
for (int i = 0; i < encodeTypeCount; i++)
{
String label = encodeMenuItems[i].getText();
if (label.equals(theEncode))
{
encodeMenuItems[i].setSelected(true);
break;
}
}
}
/**
*
*/
private void thisFrameInit()
{
getMenu();
setTabbedPaneToLast();
tabbedPane.addMouseListener(this);
this.getContentPane().add(tabbedPane);
screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
// 将本窗口全屏化
this.setSize(screenDimension.width, screenDimension.height - 30);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
setLocation(0, 0);
setVisible(true);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
shutdown();
}
});
isFrameInited = true;
}
/**
* @param string
* @return
*/
private JPanel createFileAreaPanel(String fileContent, String detail)
{
JPanel filePanel = new JPanel();
JTextArea textArea = null;
textArea = new JTextArea(fileContent);
textArea.setTabSize(tabSize);
textArea.addKeyListener(this);
allTextAreas.add(textArea);
if (detail == null)
{
detail = "";
}
JTextField fileDetailText = new JTextField(detail);
fileDetailText.setEditable(false);
allFilePropertyTextFields.add(fileDetailText);
filePanel.setLayout(new BorderLayout());
filePanel.add(new JScrollPane(textArea));
filePanel.add(fileDetailText, "South");
allTextPanels.add(filePanel);
return filePanel;
}
private void shutdown()
{
this.dispose();
Vector newContent = new Vector();
for (int i = 0; i < fileInfors.size(); i++)
{
FileInfor infor = (FileInfor)fileInfors.get(i);
if (infor instanceof NormalFileInfor)
{
newContent.add(infor.getPath());
}
}
try
{
previousOpenedFilesInfor.writeListSimple(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
}
http://blog.csdn.net/pauliuyou