Java文件操作大全(4)

来源:互联网 发布:域名到期时间影响seo 编辑:程序博客网 时间:2024/06/06 10:55

78.拷贝文件名复制文件
package p1;
import java.io.*;
import java.awt.*;
import java.awt.datatransfer.*;
public class VCFileCopy {
public static void main(String[] args) {
// TODO Auto-generated method stub
//
// 取得系统剪贴板里可传输的数据构造的Java对象
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
.getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等
// 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字

String s = (String) t.getTransferData(DataFlavor.stringFlavor);
// 同样, 因为Transferable中的DataFlavor是多种类型的,
// 所以传入DataFlavor这个参数, 指定要取得哪种类型的Data.
System.out.println(s);
int bytesum = 0;
int byteread = 0;
File oldfile = new File(s);
try {
if (oldfile.exists()) { // 文件存在时
FileInputStream inStream = new FileInputStream(oldfile); // 读入原文件
FileOutputStream fs = new FileOutputStream(new File(
"C:\\"
,
oldfile.getName()));
byte[] buffer = new byte[5120];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

79.开源程序库Xercesc-C++代码工程中内联
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class InlineXercesc {
private final String filter = ".cpp";

private ArrayList<String> all = new ArrayList<String>();

private LinkedList<String> fal2 = new LinkedList<String>();

private static String CurDir = System.getProperty("user.dir");

private void doSearch(String path) {
File filepath = new File(path);
if (filepath.exists()) {
if (filepath.isDirectory()) {
File[] fileArray = filepath.listFiles();
for (File f : fileArray) {
if (f.isDirectory()) {
doSearch(f.getPath());
} else {
if (f.getName().indexOf(filter) >= 0) {
for (String file : all) {
if (file.substring(file.lastIndexOf("\\") + 1)
.equals(f.getName())) {
fal2.add(f.getAbsolutePath());
}
}
}
}
}
} else {
System.out.println("Couldn't open the path!");
}
} else {
System.out.println("The path had been apointed was not Exist!");
}
}

public InlineXercesc(String lib) throws IOException {
String SourceLib = "D:\\Desktop\\大项目\\xerces-c-3.0.1\\src";
Pattern pattern = Pattern.compile("include.*?" + lib + ".*?>"); // 第一个参数为需要匹配的字符串
Matcher matcher = pattern.matcher("");
LinkedList<String>fal = new LinkedList<String>();
File delfile = new File(CurDir);
File[] files2 = delfile.listFiles();
for (int l = 0; l < files2.length; l++) {
if (files2[l].isDirectory()) {
String enumDir = CurDir + "\\" + files2[l].getName() + "\\";
LinkedList<String>folderList = new LinkedList<String>();
folderList.add(files2[l].getAbsolutePath());
while (folderList.size() > 0) {
File file = new File(folderList.poll());
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
String fileStr = files[i].getAbsolutePath(); // 第2个参数开始,均为文件名。
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(fileStr)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println("Cannot read '" + fileStr
+ "': " + e.getMessage());
continue;
}
StringBuilder sb = new StringBuilder(2048);
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
sb.append(line.replace(
line.substring(line.indexOf("<"),
line.lastIndexOf("/") + 1),
"\"").replace('>', '\"'));
line = line.substring(
line.indexOf("<") + 1,
line.lastIndexOf(">")).replace('/',
'\\');
fal.add(SourceLib + "\\" + line);
} else {
sb.append(line);
}
sb.append("\r\n");
}
br.close(); // 关闭文件
FileWriter fw2 = new FileWriter(fileStr);
fw2.write(sb.toString());
fw2.flush();
fw2.close();
}
}
}
while (fal.size() > 0) {
String file = fal.poll(); // 第2个参数开始,均为文件名。
String targetPath = enumDir
+ file.substring(file.lastIndexOf("\\") + 1);
if (!new File(targetPath).exists()) {
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(file)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println("Cannot read '" + file + "': "
+ e.getMessage());
continue;
}
FileWriter fw = new FileWriter(targetPath);
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
fal.add(SourceLib
+ "\\"
+ line.substring(line.indexOf("<") + 1,
line.lastIndexOf(">")).replace(
'/', '\\'));
line = line.replace(line.substring(line
.indexOf("<"),
line.lastIndexOf("/") + 1), "\"");
line = line.replace(">", "\"");

}
fw.write(line + "\r\n");
}
fw.flush();
fw.close();
br.close(); // 关闭文件

}
}
LinkedList<String>folderListArr = new LinkedList<String>();
folderListArr.add(CurDir);
while (folderListArr.size() > 0) {
File file = new File(folderListArr.poll());
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderListArr.add(files[i].getPath());
} else {
if (files[i].getName().substring(
files[i].getName().lastIndexOf("."))
.equals(".hpp"))
all.add(files[i].getAbsoluteFile().toString()
.replace(".hpp", ".cpp"));
}
}
}
int count = 1;
while (count > 0) {
doSearch(SourceLib);
all.clear();
while (fal2.size() > 0) {
String file1 = fal2.poll(); // 第2个参数开始,均为文件名。
String targetPath = enumDir
+ file1.substring(file1.lastIndexOf("\\") + 1);
if (!new File(targetPath).exists()) {
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(file1)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println("Cannot read '" + file1
+ "': " + e.getMessage());
continue;
}
FileWriter fw;
try {
fw = new FileWriter(targetPath);
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
fal2.add(SourceLib
+ "\\"
+ line.substring(
line.indexOf('<') + 1,
line.lastIndexOf('>'))
.replace('/', '\\'));
all.add(fal2.getLast().replace(".hpp",
".cpp"));
line = line.replace(line.substring(line
.indexOf('<'), line
.lastIndexOf('/') + 1), "\"");
line = line.replace('>', '\"');
}
fw.write(line + "\r\n");
}
fw.flush();
fw.close();
br.close(); // 关闭文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
count = all.size();
}
}
}
}

public static void main(String[] args) {
try {
new InlineXercesc("xercesc");
// 将数据写入文件
try {
FileWriter fw = new FileWriter(CurDir + "\\DetailCpp.cmd");
fw.write("copy StdAfx.cpp+*.c+*.cpp " + CurDir
+ "\\StdAfx.cpp && del *.c && del *.cpp");
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
}
}
}

80.提取包含头文件列表
import java.io.*;
import java.util.regex.*;
import java.util.*;
public class InlineExt {
private String CurDir = System.getProperty("user.dir");
public InlineExt() {
Pattern pattern = Pattern.compile("include.*?\".*?.hpp\""); // 第一个参数为需要匹配的字符串
Matcher matcher = pattern.matcher("");
File delfile = new File(CurDir);
File[] files2 = delfile.listFiles();
for (int l = 0; l < files2.length; l++) {
if (files2[l].isDirectory()) {
Set<String>ts = new LinkedHashSet<String>();
File file = new File(files2[l].getPath(), "StdAfx.cpp");
BufferedReader br = null;
FileWriter fw = null;
String line;
try {
br = new BufferedReader(new FileReader(file)); // 打开文件
while ((line = br.readLine()) != null) {
matcher.reset(line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
ts.add(line.substring(line.indexOf('\"') + 1, line
.lastIndexOf('\"')));
}
}
Iterator<String>it = ts.iterator();
File file2 = new File(files2[l], "ReadMe.txt");
if (file2.exists()) {
fw = new FileWriter(file2);
while (it.hasNext()) {
fw.write("#include \"" + it.next() + "\"\r\n");
}
}
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println("Cannot read '" + file + "': "
+ e.getMessage());
continue;
} finally {
try {
if (br != null)
br.close();
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
new InlineExt();
}
}

81.剪贴扳转换成打印字符
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
public class ClipBoard {
public static void main(String[] args) {
// 取得系统剪贴板里可传输的数据构造的Java对象 
Transferable t = Toolkit.getDefaultToolkit() 
.getSystemClipboard().getContents(null); 
try { 
if (t != null 
&& t.isDataFlavorSupported(DataFlavor.stringFlavor)) { 
// 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等 
// 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字 
String s = (String) t 
.getTransferData(DataFlavor.stringFlavor); 
String[]arr=s.split("\n");
StringBuilder sb=new StringBuilder(1024);
for(String ss:arr) {
if(!ss.trim().equals("")){
sb.append("w.WriteLine(\"ECHO " + ss.replace("^", "^^").replace("&", "^&").replace(":", "^:").replace(">", "^>").replace("<", "^<").replace("|", "^|").replace("\"", "^\"").replace("\\", "\\\\").replace("\"", "\\\"") + "\");");
sb.append("\r\n");
}
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(sb.toString());
clipboard.setContents(tText, null);

} catch (UnsupportedFlavorException ex) { 
ex.printStackTrace(); 
} catch (IOException ex) { 
ex.printStackTrace(); 
}
}
}

82.把JButton或JTree组件写到一个流中
/*
由于JButton和JTree都已经实现了Serializable接口,因此你所说的问题是可以做到的。
使用ObjectInputStream读取文件中的对象,使用ObjectOutputStream把对象写入文件。如:
*/
/*
import java.io.*;
import javax.swing.*;
*/
public class Save {
public static void main(String[] args) {

// Write
JButton button = new JButton("TEST Button");
JTree tree = new JTree();
try {
ObjectOutputStream outForButton = new ObjectOutputStream(
new FileOutputStream("button"));
outForButton.writeObject(button);
outForButton.close();
ObjectOutputStream outForTree = new ObjectOutputStream(
new FileOutputStream("tree"));
outForTree.writeObject(tree);
outForTree.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read

try {
ObjectInputStream inForButton = new ObjectInputStream(
new FileInputStream("button"));
JButton buttonReaded = (JButton) inForButton.readObject();

ObjectInputStream inForTree = new ObjectInputStream(
new FileInputStream("tree"));
JTree treeReaded = (JTree) inForTree.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

83.注册全局热键
//http://hi.baidu.com/ekou/blog/item/81cd52087a305bd463d986e4.html
//http://www.blogjava.net/Files/walsece/jintellitype.rar
//http://commons.apache.org/logging/
commons-loggins.jar


所谓系统级热键就是指一组快捷键,不论当前系统焦点在哪个程序中,只要按下该键,程序就能够捕捉该事件并进行相关处理。该功能在应用程序中是非常有用的,比如系统自带的 “win+L”自动锁屏,QQ中默认的“ctrl+alt+Z”自动打开当前的消息窗口等等。 Java中的事件监听机制虽然功能强大,但是当系统焦点脱离该程序时也无能为力。要实现该功能必须调用系统的钩子函数,因此在java中也必须通过jni调用来实现,但是对于不熟悉系统函数或者其他编成语言的朋友来说却是个难题。 以前实现类似的功能都是自己通过c调用系统的钩子函数然后再通过jni调用,自己写的东西只要能满足简单的需求即可,因此功能和程序结构也比较简单。后来在国外的一个网站上发现了一个组件“jintellitype”帮我们封装了绝大部分的功能,而且结构上也采用java中的事件监听机制,我们只要在程序中通过注册即可实现,下面是一个简单的例子:

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;

public class HotKey implements HotkeyListener {
static final int KEY_1 = 88;
static final int KEY_2 = 89;
static final int KEY_3 = 90;

/**
* 该方法负责监听注册的系统热键事件

* @param key:触发的热键标识
*/
public void onHotKey(int key) {
switch (key) {
case KEY_1:
System.out.println("ctrl+alt+I 按下.........");
break;
case KEY_2:
System.out.println("ctrl+alt+O 按下.........");
break;
case KEY_3:
System.out.println("系统退出..........");
destroy();
}

}

/**
* 解除注册并退出
*/
void destroy() {
JIntellitype.getInstance().unregisterHotKey(KEY_1);
JIntellitype.getInstance().unregisterHotKey(KEY_2);
JIntellitype.getInstance().unregisterHotKey(KEY_3);
System.exit(0);
}

/**
* 初始化热键并注册监听事件
*/
void initHotkey() {
// 参数KEY_1表示改组热键组合的标识,第二个参数表示组合键,如果没有则为0,该热键对应ctrl+alt+I
JIntellitype.getInstance().registerHotKey(KEY_1,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'I');
JIntellitype.getInstance().registerHotKey(KEY_2,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'O');
JIntellitype.getInstance().registerHotKey(KEY_3,
JIntellitype.MOD_CONTROL + JIntellitype.MOD_ALT, (int) 'X');

JIntellitype.getInstance().addHotKeyListener(this);
}

public static void main(String[] args) {
HotKey key = new HotKey();
key.initHotkey();

// 下面模拟长时间执行的任务
while (true) {
try {
Thread.sleep(10000);
} catch (Exception ex) {
break;
}
}
}
}

偶尔,我们可以给用户添加一些快捷键,不管现在焦点在哪里。

有个做法就是,任何组建上注册你的监听器,但显然,这不是一个好做法

java的toolkit可以直接添加一个监听器,

一下就是示例

Toolkit toolkit = Toolkit.getDefaultToolkit();

toolkit.addAWTEventListener(capListener, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK| AWTEvent.WINDOW_EVENT_MASK);

实现一个监听器:

class CapListener implements AWTEventListener {

public void eventDispatched(AWTEvent event) {

}

}
这就可以了

84.菜单勾选/取消完成后关闭计算机
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -f -s -t 0");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 内部线程类 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回调接口 */
interface ICallBack
{
public void output();
}

85.菜单勾选/取消完成后重新启动计算机
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -f -r -t 0");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 内部线程类 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回调接口 */
interface ICallBack
{
public void output();
}

86.菜单勾选/取消完成后注销计算机
//import java.io.*;
public class Parent implements ICallBack
{
public static void main(String[] args) 
{
Parent parent=new Parent();
Thread son=new Son(parent);
son.start();
}
public void output()
{
try {
Runtime.getRuntime().exec("shutdown -l");
} catch (IOException e) {
e.printStackTrace();
}
}
}

/* 内部线程类 */
class Son extends Thread
{
private ICallBack event;
public Son(ICallBack callback)
{
event=callback;
}
public void run()
{
try
{
java.text.SimpleDateFormat fmt=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(true)
{
Thread.currentThread().sleep(3000);
event.output(fmt.format(new java.util.Date()));
Thread.currentThread().sleep(3000);
}
}
catch (Exception e)
{
}
}
}

/* 回调接口 */
interface ICallBack
{
public void output();
}

87.菜单勾选/取消开机自启动程序
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*; 
//import java.util.*; 
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
RegistryValue v = new RegistryValue("run", ValueType.REG_SZ, "data");
r.setValue(v);

/////////////////////////////////////////////////////////////


0 0