新手使用Java(持续更新)

  最近想把工作学习中碰到的一些问题都记录下来,所以创建了一系列文章来记录遇到的问题,这样以后就不用反复到网上找资料了。


  Java读写文件

  java读文件

  直接上代码:

 

package com.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class MyFileReader {
	private String filename;
	private BufferedReader reader = null;
	private String nextline = null;
	public MyFileReader(String filename) {
		this.filename = filename;
		File file = new File(this.filename);
		try {
			reader = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public boolean hasMore() {
		try {
			nextline = reader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (nextline != null) return true;
		return false;
	}
	
	public String getNext() {
		return nextline;
	}
	
	public void close() {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  Java写文件

 

public void write() {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(tarFilename));
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			bw.write("content" + System.getProperty("line.separator"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


Java中重写equals和hashcode方法

这里有两篇比较好的资料,讲解Java中的euqlas和hashcode方法的文章。

http://blog.chinaunix.net/uid-11798215-id-3453118.html

http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java

这里再贴一段在jdk中,对hashcode方法和equals方法的描述

   * <li>If two objects are equal according to the <tt>equals(Object)</tt>
     *     method, then calling the <code>hashCode</code> method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the <tt>hashCode</tt> method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hashtables.


意思就是

hashCode()的返回值和equals()的关系如下:

如果 x.equals(y) 返回 “true” ,那么 x 和 y 的 hashCode() 必须相等。
如果 x.equals(y) 返回 “false” ,那么 x 和 y 的 hashCode() 有可能相等,也有可能不等。



Java中的synchronized主要是用来进行同步的。synchronized锁住的,是一个对象。只要分清楚这个,那一些现象就会比较好理解。
1、synchronized非静态方法
public synchronized void test1() {
		
	}
	
	public void test1() {
		synchronized(this) {
			
		}
	}
上面方法是等价的,所以,使用synchronized修改的非静态方法,实际上是对这个对象加锁了。

2、synchronized静态方法
public synchronized static void test() {
		
	}
	
	public void test() {
		synchronized(this.getClass()) {
			
		}
	}
上面两个方法是等价的,因为synchronized静态方法,实际上是锁住了Class对象。

3、
public synchronized  static void test1() {
		System.out.println("test1");
		while (true)
			;
	}

	public void test2() {
		synchronized (this) {
			System.out.println("test2");
			while (true)
				;
		}
	}

public static void test_1() {
		final SynchronizedTest instance1 = new SynchronizedTest();

		new Thread(new Runnable() {

			public void run() {
				instance1.test1();
			}

		}).start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(new Runnable() {

			public void run() {
				instance1.test2();
			}

		}).start();
	}

上面的代码中,输出的结果是
test1
test2
是因为test1是锁住了Class对象,test2所以了instance1对象。所以不能达到同步的效果。只要去掉test1中的static就可以了。

Java查找class在哪个jar中
代码如下: 微笑
package com.tool;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;

public class LoadClassFromJar {
	
	private List<String> jarsFilePath;
	private ClassLoader customizedClassLoader;
	private String targetClass;

	//init jarFilePath and targetClass
	public void init() {
		
	}
	
	public String getTargetPath() throws ClassNotFoundException {
		Class clazz = customizedClassLoader.loadClass(targetClass);
		ProtectionDomain pd = clazz.getProtectionDomain();
		CodeSource source = pd.getCodeSource();
		return source.getLocation().toString();
	}
	
	public void loadJars() throws MalformedURLException {
		List<URL> urls = getJarUrls();
		URL[] urlArray = urls.toArray(new URL[urls.size()]);
		customizedClassLoader = new URLClassLoader(urlArray , this.getClass().getClassLoader());
	}
	
	public List<URL> getJarUrls() throws MalformedURLException {
		File[] jars = getJars();
		List<URL> ret = new ArrayList<URL>();
		
		for (File jar : jars) {
			ret.add(jar.toURI().toURL());
		}
		return ret;
	}
	
	public File[] getJars() {
		List<File> ret = new ArrayList<File>();
		
		for (String path : jarsFilePath) {
			File file = new File(path);
			if (file.isDirectory()) {
				for (File subFile : file.listFiles()) {
					if (subFile.getName().endsWith(".jar")) {
						ret.add(subFile);
					}
				}
			}
			else if (file.getName().endsWith(".jar")){
				ret.add(file);
			}
		}
		return ret.toArray(new File[ret.size()]);
	}
}

去除Java项目中的CVS
当时碰到要把项目copy给别人,但是项目中有很多CVS的相关信息,特别是账号信息,不希望给别人,所以就希望能把这些文件去去掉。这样文件也会小很多。下面就代码:
package com.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;

public class ClearCVSFile {
	
	private static final String FROM_PATH = "";
	private static final String TO_PATH = "";
	private FilenameFilter filter;
	
	public static void main(String args[]) {
		ClearCVSFile instance = new ClearCVSFile();
		instance.init();
		instance.process();
		System.out.println("success");
	}
	
	public void init() {
		filter = new FilenameFilter() {
			public boolean accept(File file , String name) {
				return (!name.endsWith("CVS"));
			}
		};
	}
	
	public void process() {
		File from_file = new File(FROM_PATH);
		File to_file = new File(TO_PATH);
		copy(from_file , to_file , from_file);
	}
	
	public void copy(File from_root , File to_root , File current) {
		File[] files = current.listFiles(filter);
		for (File file : files) {
			if (file.isDirectory()) {
				copy(from_root , to_root , file);
			}
			else {
				String path = file.getAbsolutePath().substring(from_root.getAbsolutePath().length() + 1);
				File toFile = new File(to_root , path);
				copySingleFile(file , toFile);
			}
		}
	}
	
	public void copySingleFile(File from , File to){
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			to.getParentFile().mkdirs();
			in = new FileInputStream(from);
			out = new FileOutputStream(to);
			
			byte[] buf = new byte[2048];
			int len = 0;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (in!= null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}


Eclipse调试技巧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值