Menu Home

java

java的坑:ProcessBuilder处理通配符

喝着可乐听着歌;敲着代码哼着曲。没有一点点防备,就这样掉进了坑里。 下面的代码是用通过ProcessBuilder调用命令来删除以system_开头的文件。 因为之前删除具体文件的时候这个方法非常好用,于是就想当然了。 ArrayList<String> cmd = new ArrayList<String>(); cmd.add(“rm”); cmd.add(“-vrf”); cmd.add(“/tmp/system_*”); ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); try { Process process = pb.start(); InputStream is = process.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(is)); String line; while ((line = read.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); […]

Java: 判断符号连接

/** * Determines whether the specified file is a Symbolic Link rather than an actual file. * <p> * Will not return true if there is a Symbolic Link anywhere in the path, * only if the specific file is. * <p> * <b>Note:</b> the current implementation always returns {@code […]

Java:线程安全的单例

public class Singleton { private static class SingletonHolder { private static Singleton sSingleton = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.sSingleton; } private Singleton() { } } 基于以下事实: JVM加载class是线程安全的。 class的static成员在类首次加载时初始化。

Java DOM设置XML缩进

TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(mDocument); transformer.setOutputProperty(OutputKeys.INDENT, “yes”); transformer.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “4”);//缩进宽度 transformer.setOutputProperty(OutputKeys.METHOD, “xml”); transformer.setOutputProperty(OutputKeys.ENCODING, “UTF-8”);

Java Enum

Java的Enum搞的越来越强大,用着也越来越别扭。看看下面的代码: public class TestJavaEnum { static enum WorkDay { Mon(“Monday”), Tue(“Tuesday”), Wed(“Wednesday”), Thu(“Thursday”), Fri(“Friday”); private String mDay; private WorkDay(String day) { mDay = day; } @Override public String toString() { return mDay; } } public static void main(String[] args) { WorkDay[] workDays = WorkDay.values(); System.out.println(“——WorkDay——“); for (int i = 0; […]

XPath去除XML空行

XPath xp = XPathFactory.newInstance().newXPath(); NodeList nl = null; try { nl = (NodeList) xp.evaluate(“//text()[normalize-space(.)=”]”, mDocument, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } for (int i = 0; i < nl.getLength(); ++i) { Node node = nl.item(i); node.getParentNode().removeChild(node); }

[转]XPath简介

结点类型 XPath中有七种结点类型:元素、属性、文本、命名空间、处理指令、注释以及文档节点(或成为根节点)。 文档的根节点即是文档结点;对应属性有属性结点,元素有元素结点。 常用路径表达式 表达式 描述 nodename 选取此节点的所有子节点 / 从根节点选取 // 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置 . 选取当前节点 .. 选取当前节点的父节点 @ 选取属性 例如有文档: <?xml version=”1.0″ encoding=”ISO-8859-1″?> Harry Potter 29.99 Learning XML 39.95 则:

Java DOM 设置XML STANDALONE

public void save2file() { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(mDocument); transformer.setOutputProperty(OutputKeys.INDENT, “yes”); transformer.setOutputProperty(OutputKeys.STANDALONE, “yes”); PrintWriter pw = new PrintWriter(new FileOutputStream(mFileName)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } } 输出: <?xml version=”1.0″ encoding=”utf-8″ standalone=”no”?> 这里的 […]

使用FileChannel拷贝文件

使用FileChannel拷贝文件的效率比逐字节拷贝要更高效,但是FileChannel有一个限制:操作的文件大小不能大于2GB public void copy(File src, File dst) throws IOException { FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inStream.close(); outStream.close(); }

使用Invocation API调用Java类

InvocationApiTest.java import java.io.*; public class InvocationApiTest { public static void main(String[] args) { System.out.println(args[0]); } } invocationApi.c #include <jni.h> int main() { JNIEnv* env; JavaVM* vm; JavaVMInitArgs vm_args; JavaVMOption options[1]; jint res; jclass cls; jmethodID mid; jstring jstr; jclass stringClass; jobjectArray args; //1.生成Java虚拟机选项 options[0].optionString = “-Djava.class.path=.”; vm_args.version = JNI_VERSION_1_6; vm_args.options […]

Java语言中对象的部分序列化

public class TestExternalizable implements Externalizable { //只对下面2个变量序列化 int No; String name; //下面的变量没有被序列化 int age = 0; public TestExternalizable() { // 在恢复Externalizable对象的时候,默认构造函数会被调用,这一点跟恢复一个Serializable对象不同 System.out.println(“Default Constructor”); } public TestExternalizable(int No, String name, int age) { System.out.println(“Other Constructor”); this.name = name; this.No = No; this.age = age; } @Override public String toString() { return […]

Java基本IO操作(备忘)

#java 1.1 public class IODemo { public static void main(String[] args) { try { // 1a.Reading input by lines BufferedReader in = new BufferedReader(new FileReader(args[0])); String s, s2 = new String(); while ((s = in.readLine()) != null) { s2 += s + “\n”; } in.close(); // 1b.Reading standard input BufferedReader […]

Java构建类型安全的枚举类型

在《Java编程思想-网络版》一书中看到一段有意思的代码。 先来看一段Java实现C/C++枚举效果的非类型安全的版本: public interface Months { int JANUARY = 1, FEBRUARY = 2, MARCH = 3, APRIL = 4, … …; } 上面的代码实际上是在利用Java中interface的成员变量会自动成为public static final的事实,这样我们可以使用Months.JANUARY的方法来引用这些值。但是这个方法的缺陷是非类型安全的,因为我们最终获得的其实是个int。这种方法带来的好处只是减少了硬编码。 接下来看看Bruce Eckel提供的类型安全的版本: public final class Month2 { private String name; private Month2(String nm) { name = nm; } public String toString() { return name; } […]

Java线程同步方法

CountDownLatch CountDownLatch主要用来等待一系列线程都完成后,再继续下一步的执行,类似于C++中的join。 import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchExample { public static void main(String[] args) { ExecutorService pool = Executors.newCachedThreadPool(); final CountDownLatch doneLatch = new CountDownLatch(10); for(int i = 0; i < 10; i++) { Runnable runnable = new Runnable() { @Override public void run() { try { […]