有个文本内容如下:我现在想对其中一行进行修改,如把
compressnet 2/udp # Management Utility 改成
compressnet 34/udp # xiugai并在最后面加上一行
222 345345/udp # 222或者删除某一行请问我要怎么做呢???希望能给个实例看看
# Well known service port numbers -*- mode: fundamental; -*-
# From the Nmap security scanner ( http://www.insecure.org/nmap/ )
#
# $Id: nmap-services 6563 2007-12-19 01:26:32Z doug $
# For a HUGE list of services (including these and others),
# see http://www.graffiti.com/services
tcpmux 1/tcp # TCP Port Service Multiplexer [rfc-1078]
tcpmux 1/udp # TCP Port Service Multiplexer
compressnet 2/tcp # Management Utility
compressnet 2/udp # Management Utility
compressnet 3/tcp # Compression Process
compressnet 3/udp # Compression Process
rje 5/tcp # Remote Job Entry
rje 5/udp # Remote Job Entry
compressnet 2/udp # Management Utility 改成
compressnet 34/udp # xiugai并在最后面加上一行
222 345345/udp # 222或者删除某一行请问我要怎么做呢???希望能给个实例看看
# Well known service port numbers -*- mode: fundamental; -*-
# From the Nmap security scanner ( http://www.insecure.org/nmap/ )
#
# $Id: nmap-services 6563 2007-12-19 01:26:32Z doug $
# For a HUGE list of services (including these and others),
# see http://www.graffiti.com/services
tcpmux 1/tcp # TCP Port Service Multiplexer [rfc-1078]
tcpmux 1/udp # TCP Port Service Multiplexer
compressnet 2/tcp # Management Utility
compressnet 2/udp # Management Utility
compressnet 3/tcp # Compression Process
compressnet 3/udp # Compression Process
rje 5/tcp # Remote Job Entry
rje 5/udp # Remote Job Entry
点添加按钮后,从输入框里读取内容,然后把这些内容写进文本中
点删除按钮后,删除某一行
点修改按钮就修改某一行
package com.file;import java.io.*;
/** *//**
*
* 功能描述:创建TXT文件并进行读、写、修改操作
*
* @author angler
*
*
*/
public class ReadWriteFile {
public static BufferedReader bufread;
//指定文件路径和名称
private static String path = "D:/suncity.txt";
private static File filename = new File(path);
private static String readStr ="";
/** *//**
* 创建文本文件.
* @throws IOException
*
*/
public static void creatTxtFile() throws IOException{
if (!filename.exists()) {
filename.createNewFile();
System.err.println(filename + "已创建!");
}
}
/** *//**
* 读取文本文件.
*
*/
public static String readTxtFile(){
String read;
FileReader fileread;
try {
fileread = new FileReader(filename);
bufread = new BufferedReader(fileread);
try {
while ((read = bufread.readLine()) != null) {
readStr = readStr + read+ "\r\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("文件内容是:"+ "\r\n" + readStr);
return readStr;
}
/** *//**
* 写文件.
*
*/
public static void writeTxtFile(String newStr) throws IOException{
//先读取原有文件内容,然后进行写入操作
String filein = newStr + "\r\n" + readStr + "\r\n";
RandomAccessFile mm = null;
try {
mm = new RandomAccessFile(filename, "rw");
mm.writeBytes(filein);
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
} finally {
if (mm != null) {
try {
mm.close();
} catch (IOException e2) {
// TODO 自动生成 catch 块
e2.printStackTrace();
}
}
}
}
/** *//**
* 将文件中指定内容的第一行替换为其它内容.
*
* @param oldStr
* 查找内容
* @param replaceStr
* 替换内容
*/
public static void replaceTxtByStr(String oldStr,String replaceStr) {
String temp = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer(); // 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null
&& !temp.equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
} // 将内容插入
buf = buf.append(replaceStr); // 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
} br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/** *//**
* main方法测试
* @param s
* @throws IOException
*/
public static void main(String[] s) throws IOException {
ReadWriteFile.creatTxtFile();
ReadWriteFile.readTxtFile();
ReadWriteFile.writeTxtFile("20080808:12:13");
// ReadWriteFile.replaceTxtByStr("ken", "zhang");
}
}
有swing操作窗口的。
代码有些多,lz慢慢看。主Frame,画面由此main函数启动:package fileope.frame;import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;public class FileOperatorFrame extends JFrame {
private AllDataPnl alldaPanel = null; private JButton addBtn = null; private AddDialog addDlg = null; public FileOperatorFrame(String title) {
super(title);
init();
} private void init() {
alldaPanel = new AllDataPnl(); addBtn = new JButton("Add");
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDlg = new AddDialog("Add", alldaPanel);
} });
this.getContentPane().add(alldaPanel, BorderLayout.CENTER);
this.getContentPane().add(addBtn, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(400, 600);
this.pack(); alldaPanel.updateTable();
} public static void main(String args[]) {
FileOperatorFrame fof = new FileOperatorFrame("FILE OPE");
}
}table,用来显示文件内的内容package fileope.frame;import java.awt.BorderLayout;
import java.awt.Color;import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;public class AllDataPnl extends JPanel {
private JTable allDataTbl = null; private TableModel tableModel = null; private ButtonEditor btnEditor = null; private ButtonRenderer btnRenderer = null; public AllDataPnl() {
tableModel = new TableModel();
allDataTbl = new JTable(tableModel);
allDataTbl.setBackground(Color.white); TableColumnModel tcm = allDataTbl.getColumnModel(); //3 col
btnEditor = new ButtonEditor(new JCheckBox());
btnRenderer = new ButtonRenderer();
tcm.getColumn(2).setCellRenderer(btnRenderer);
tcm.getColumn(2).setCellEditor(btnEditor); tcm.getColumn(0).setPreferredWidth(5);
tcm.getColumn(1).setPreferredWidth(340);
tcm.getColumn(2).setPreferredWidth(50);
JScrollPane jsp = new JScrollPane(allDataTbl);
this.add(jsp, BorderLayout.CENTER);
} public void updateTable() {
tableModel.makeViewData();
allDataTbl.updateUI();
} public TableModel getTableModel() {
return tableModel;
}
}
TableModel,用来实现table内部细节
package fileope.frame;import java.io.DataInputStream;
import java.io.FileInputStream;
import java.util.Vector;import javax.swing.JButton;
import javax.swing.table.AbstractTableModel;import fileope.CmnUtil;public class TableModel extends AbstractTableModel {
private Vector content = null; private String[] titlename = { "No", "content", "" }; private JButton modifyBtn = null; private JButton delBtn = null; private static final String BTN_TEXT = "Del"; public TableModel() {
content = new Vector();
} public TableModel(int count) {
content = new Vector(count);
} public void makeViewData() {
try {
DataInputStream dis = new DataInputStream(new FileInputStream(
"input.txt"));
String line = null;
Vector v = null;
int no = 1;
if (content != null && content.size() != 0)
content.clear();
while ((line = dis.readLine()) != null) {
v = new java.util.Vector(3);
v.add(0, new Integer(no++));
v.add(1, line);
v.add(2, BTN_TEXT);
content.add(v);
}
} catch (Exception e) {
e.printStackTrace();
}
} public void addRow(String data) {
Vector v = new Vector(3);
v.add(0, new Integer(content.size()));
v.add(1, data);
v.add(2, BTN_TEXT);
content.add(v);
} public void removeRow(int row) {
content.remove(row);
} public void removeRows(int row, int count) {
for (int i = 0; i < count; i++) {
if (content.size() > row) {
content.remove(row);
}
}
} /**
* 讓表格中某些値可修改,但需要setValueAt(Object value, int row, int col)方法配合才能使修改生效
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return false;
}
return true;
} /**
* 使修改内容生效
*/
public void setValueAt(Object value, int row, int col) { ((Vector) content.get(row)).remove(col);
((Vector) content.get(row)).add(col, value);
if (CmnUtil.saveFile(this.getContent())) {
javax.swing.JOptionPane.showMessageDialog(null, "save success");
} else {
javax.swing.JOptionPane.showMessageDialog(null, "save fail");
} this.fireTableCellUpdated(row, col);
} public String getColumnName(int col) {
return titlename[col];
} public int getColumnCount() {
return titlename.length;
} public int getRowCount() {
// content.elementAt(0);
return content.size();
} public Object getValueAt(int row, int col) {
return ((Vector) content.get(row)).get(col);
} /**
* 返回數據類型
*/
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
} public Vector getContent() {
return content;
}
}
向table中加入button按钮列package fileope.frame;import java.awt.Color;
import java.awt.Component;import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;public class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
} public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(new Color(184, 208, 200));
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(new Color(217, 236, 210));
}
setText((value == null) ? "" : value.toString());
return this;
}
}每行的删除按钮package fileope.frame;import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JTable;import fileope.CmnUtil;public class ButtonEditor extends DefaultCellEditor {
protected JButton button; private String label; private boolean isPushed; private int rowcount; private JTable table; public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton("Set");
button.setOpaque(true); button.addActionListener(new buttonClickListener());
} public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
rowcount = row;
this.table = table;
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(new Color(182, 208, 200));
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
} public Object getCellEditorValue() {
if (isPushed) {
}
isPushed = false;
return new String(label);
} public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
} protected void fireEditingStopped() {
super.fireEditingStopped();
} private class buttonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
TableModel tabelModel = ((fileope.frame.TableModel) table
.getModel());
tabelModel.removeRow(rowcount); if (CmnUtil.saveFile(tabelModel.getContent())) {
javax.swing.JOptionPane.showMessageDialog(null, "save success");
} else {
javax.swing.JOptionPane.showMessageDialog(null, "save fail");
}
}
}
}
package fileope.frame;import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;import fileope.CmnUtil;public class AddDialog extends JDialog { private JTextField data = null; private AllDataPnl all = null; private JButton exeBtn = null; public AddDialog(String title, AllDataPnl m) {
this.setTitle(title);
all = m;
init(); this.setSize(400, 200);
this.setVisible(true);
this.pack();
} private void init() {
JLabel titil = new JLabel("add content:");
data = new JTextField(30);
exeBtn = new JButton("add"); exeBtn.addActionListener(new ExeBtnClick(this));
JPanel pnl = new JPanel(new FlowLayout());
pnl.add(titil);
pnl.add(data);
pnl.add(exeBtn);
this.add(pnl);
} private class ExeBtnClick implements ActionListener {
private JDialog dlg = null; public ExeBtnClick(JDialog dlg) {
this.dlg = dlg;
} public void actionPerformed(ActionEvent e) {
TableModel tm = all.getTableModel();
tm.addRow(data.getText()); if (CmnUtil.saveFile(tm.getContent())) {
javax.swing.JOptionPane.showMessageDialog(null, "add success");
dlg.setVisible(false);
} else {
javax.swing.JOptionPane.showMessageDialog(null, "add fail");
}
all.updateTable();
} }
}
这个工具类用来保存文件,把修改或者追加,删除的操作反映到本地文件package fileope;import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;public class CmnUtil {
public static boolean saveFile(Vector content) {
boolean ret = true;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(
"input.txt"));
int size = content.size();
Vector v = null;
String line = null;
for (int lineNo = 0; lineNo < size; lineNo++) {
v = (Vector) content.get(lineNo);
line = v.get(1).toString();
dos.writeBytes(line);
if (lineNo != size - 1) {
dos.writeBytes("\n");
}
}
} catch (Exception e) {
try {
dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
ret = false;
e.printStackTrace();
}
finally
{
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
}
我在工程的目录下建立了文件 input.txt,
这个文件的路径需要根据你的需要自行修改。修改的地方在我提供你的类 TableModel 的 makeViewData方法中。
另外一个就是写的时候的路径,与前一个一致,在CmnUtil类的saveFile中。改下就好了。
PS:代码用时较短,根本没有怎么思考,想到哪写到哪。
仅供参考。