分享一个文件编辑器

pauliuyou 2010-01-27 08:32:22
文件信息封装对象


/**
*
*/
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;

}

...全文
543 27 打赏 收藏 转发到动态 举报
写回复
用AI写文章
27 条回复
切换为时间正序
请发表友善的回复…
发表回复
pauliuyou 2010-02-11
  • 打赏
  • 举报
回复
顶起来, 欢迎讨论 顶起来, 欢迎讨论
zliuzz 2010-01-29
  • 打赏
  • 举报
回复
很强大。。。但是现在木有搞界面开发
pauliuyou 2010-01-29
  • 打赏
  • 举报
回复
好主意, 看我的博客: 哈哈, 很少写博客的.
http://blog.csdn.net/pauliuyou
_千鸟 2010-01-29
  • 打赏
  • 举报
回复
楼主最好搞个下载的链接吧....
pauliuyou 2010-01-29
  • 打赏
  • 举报
回复
大家别急啊,还没发完呢.
reeves101 2010-01-29
  • 打赏
  • 举报
回复
up!
lgf11088 2010-01-29
  • 打赏
  • 举报
回复
先顶...再用...
heidaizx 2010-01-29
  • 打赏
  • 举报
回复
帮顶下
Sieben77 2010-01-29
  • 打赏
  • 举报
回复
先顶个...慢慢享用...
liujun3512159 2010-01-29
  • 打赏
  • 举报
回复
不错,谢谢了
xiesisi3 2010-01-29
  • 打赏
  • 举报
回复
不错,有撤消功能吗?
24K純帥 2010-01-29
  • 打赏
  • 举报
回复
谢谢LZ分享。。
frost0506 2010-01-28
  • 打赏
  • 举报
回复
不错~D一个~
lgm277531070 2010-01-28
  • 打赏
  • 举报
回复
look
lzlwzs04 2010-01-28
  • 打赏
  • 举报
回复
友情顶个
  • 打赏
  • 举报
回复
很长


看的想睡觉


祝福
pauliuyou 2010-01-28
  • 打赏
  • 举报
回复
大家要多顶, 我只能连续回3个.
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();
}
}
pauliuyou 2010-01-28
  • 打赏
  • 举报
回复
类FileEditor -1


/**
*
*/
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;
}
}
pauliuyou 2010-01-28
  • 打赏
  • 举报
回复
普通文件封装对象
两部分_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);
}

}


whut0802 2010-01-28
  • 打赏
  • 举报
回复
顶起来。
加载更多回复(7)

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧