Java进阶之路_重温《java编程思想》篇(六)

java异常处理机制

对于哪些具有可以失败的构造器,且需要清理的对象,每一个构造都必须包含在自己的try-finally语句块中,并且每一个对象构造之后必须跟随一个try-finally语句以确保清理。实例代码如下:

package com.exception;

public class Cleanup {

	public static void main(String[] args) {

		try{
			InputFile in = new InputFile("Cleanup.java");
			try{
				String s;
				int i = 1;
				while((s = in.getLine()) != null)
					;
			}catch(Exception e){
				System.out.println("Caught Exception int main");
				e.printStackTrace();
			}finally{
				in.dispose();
			}
		}catch(Exception e){
			System.out.println("InputFile construction failed");
		}
	}

}

字符串:

递归调用案例:

package com.string;

import java.util.ArrayList;
import java.util.List;

public class InfiniteRecursion {

	public static void main(String[] args) {

		List list = new ArrayList();
		for (int i = 0; i < 10; i++) {
			list.add(new InfiniteRecursion());
		}
		System.out.println(list);
	}
	public String toString(){
		return "InfiniteResursion address: " + this + "\n";
	}

}
使用this的时候会调用toString方法,然后又会使用到this,产生递归调用。
解决方案:应该调用Object.toString()方法,所以不应该使用this,而是使用super.toString()方法。

package com.string;

import java.util.ArrayList;
import java.util.List;

public class InfiniteRecursion {

	public static void main(String[] args) {

		List list = new ArrayList();
		for (int i = 0; i < 10; i++) {
			list.add(new InfiniteRecursion());
		}
		System.out.println(list);
	}
	public String toString(){
		return "InfiniteResursion address: " + super.toString() + "\n";
	}

}


正则表达式分组:组是用括号划分的正则表达式。例如:A(B(C))D中有三个组:组0是ABCD,组1是BC,组2是C。

以下代码给出了分组的正确用法:

package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Groups {

	private static final String POEM = 
	  "Twas brillig, and the slithy toves\n" +  
      "Did gyre and gimble in the wabe.\n" +  
      "All mimsy were the borogoves,\n" +  
      "And the mome raths outgrabe.\n" +  
      "Beware the Jabberwock, my son,\n" +  
      "The jaws that bite, the claws that catch.\n" +  
      "Beware the Jubjub bird, and shun\n" +  
      "The frumious Bandersnatch.";
	public static void main(String[] args) {

		Matcher m = Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
				.matcher(POEM);
		while(m.find()){
			for(int i = 0; i <= m.groupCount(); ++i){
				System.out.print("[" + m.group(i) + "]");
			}
			System.out.println();
		}
	}/*Output:
	[the slithy toves][the][slithy toves][slithy][toves]
	[in the wabe.][in][the wabe.][the][wabe.]
	[were the borogoves,][were][the borogoves,][the][borogoves,]
	[mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.]
	[Jabberwock, my son,][Jabberwock,][my son,][my][son,]
	[claws that catch.][claws][that catch.][that][catch.]
	[bird, and shun][bird,][and shun][and][shun]
	[The frumious Bandersnatch.][The][frumious Bandersnatch.][frumious][Bandersnatch.]
	*///:~
}

?m说明:

一般情况下,是将$与整个输入序列的末端相匹配。所以这里存在多行的情况下,我们必须显示地告诉正则表达式注意输入序列中的换行符,序列开头的?m则起到了这个作用。
不以大写字母开头的词:词边界正则表达式 “\b”。代码如下:

package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupsModify {

	private static final String POEM = 
	  "Twas brillig, and the slithy toves\n" +  
      "Did gyre and gimble in the wabe.\n" +  
      "All mimsy were the borogoves,\n" +  
      "And the mome raths outgrabe.\n" +  
      "Beware the Jabberwock, my son,\n" +  
      "The jaws that bite, the claws that catch.\n" +  
      "Beware the Jubjub bird, and shun\n" +  
      "The frumious Bandersnatch.";
	public static void main(String[] args) {

		Matcher m = Pattern.compile("\\b[a-z]\\w*\\b")
				.matcher(POEM);
		while(m.find()){
			System.out.println(m.group());
		}
	}/*Output:
	brillig
	and
	the
	slithy
	toves
	gyre
	and
	gimble
	in
	the
	wabe
	mimsy
	were
	the
	borogoves
	the
	mome
	raths
	outgrabe
	the
	my
	son
	jaws
	that
	bite
	the
	claws
	that
	catch
	the
	bird
	and
	shun
	frumious
	*///:~
}

常用的一些Pattern标记:Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.COMMENTS,详情查询文档。

补充一些,文件读取知识:

System.getProperty("user.dir")读取当前工程路径。

对于windows下,\r\n这两个字符在一起时,表示一个换行。

在执行替换过程中,操作用来替换的字符串:(该例包含了文件读写的方法,包括文本文件读取,以及二进制文件的读写):

package regext;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*! Here's a block of text to use as input to
 the regular expression matcher. Note that we'll
 first extract the block of text by looking for
 the special delimiters, then process the
 extracted block. !*/
public class TheReplacements {
	/**
	 * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
	 * 一次读取多个字节,(一次读取一个字节与字符文件读取类似)
	 */
	public void copyFileByBytes(String fileName, String toPathFile){
		File file = new File(fileName);
		File desFile = new File(toPathFile);
		InputStream is = null;
		OutputStream os = null;
		BufferedOutputStream bos = null;
		try {
			is = new FileInputStream(file);
			os = new FileOutputStream(desFile);
			bos = new BufferedOutputStream(os);
			int tempByte;
			byte[] tempBytes = new byte[100];
			while((tempByte = is.read(tempBytes)) != -1){
				bos.write(tempBytes, 0, tempByte);
			}
			bos.close();
			os.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	 /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     * 一次读取一个字符
     */
	public String readFileByChars(String fileName){
		StringBuilder result = new StringBuilder();
		File file = new File(System.getProperty("user.dir") + "\\src\\main\\java\\regext\\" + fileName);
		InputStream stream = null;
		Reader reader = null;
		try {
			stream = new FileInputStream(file);
			reader = new InputStreamReader(stream);
			int tempChar;
			while((tempChar = reader.read()) != -1){
				result.append((char)tempChar);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result.toString();
	}
	/**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     * 一次读取多个字符
     */
	public String readFileByChars2(String fileName){
		StringBuilder result = new StringBuilder();
		File file = new File(System.getProperty("user.dir") + "\\src\\main\\java\\regext\\" + fileName);
		InputStream stream = null;
		Reader reader = null;
		try {
			char[] tempChars = new char[100];
			int charRead = 0;
			stream = new FileInputStream(file);
			reader = new InputStreamReader(stream);
			while((charRead = reader.read(tempChars)) != -1){
				if((tempChars.length == charRead)){
					result.append(tempChars);
				}else{
					for(int i = 0; i < charRead; i++){
						result.append(tempChars[i]);
					}
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}
	
	public static void main(String[] args) throws Exception {
		
		TheReplacements replacement = new TheReplacements();
//		System.out.println(replacement.readFileByChars2("TheReplacements.java"));
//		String fileName = "E:\\myFiles\\pic1.jpg";
//		String toPathFile = "E:\\myPicture.jpg";
//		replacement.copyFileByBytes(fileName, toPathFile);
		String s = replacement.readFileByChars2("TheReplacements.java");
		// Match the specially-commented block of text above:
		Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
		if (mInput.find()){
			s = mInput.group(1); // Captured by parentheses
		}
		// Replace two or more spaces with a single space:
		s = s.replaceAll(" {2,}", " ");
		// Replace one or more spaces at the beginning of each
		// line with no spaces. Must enable MULTILINE mode:
		s = s.replaceAll("(?m)^ +", "");
		System.out.println(s);
		s = s.replaceFirst("[aeiou]", "(VOWEL1)");
		StringBuffer sbuf = new StringBuffer();
		Pattern p = Pattern.compile("[aeiou]");
		Matcher m = p.matcher(s);
		// Process the find information as you
		// perform the replacements:
		while (m.find())
			m.appendReplacement(sbuf, m.group().toUpperCase());
		// Put in the remainder of the text:
		m.appendTail(sbuf);
		System.out.println(sbuf);
	}/* Output :~//
	Here's a block of text to use as input to
	the regular expression matcher. Note that we'll
	first extract the block of text by looking for
	the special delimiters, then process the
	extracted block. 
	H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO
	thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll
	fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr
	thE spEcIAl dElImItErs, thEn prOcEss thE
	ExtrActEd blOck. 
	*/
} 

读取java文件中的注释(注意正则表达式中问号的用法):

package com.string;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindAnnotation {

	public static void main(String[] args) {

		String fileStr = getFileStr("E:\\fileRegext\\JGrep.java");
//		System.out.println(fileStr);
//		Pattern p = Pattern.compile("//[^\n]*");
//		Pattern p = Pattern.compile("/\\*(\\s|.)*?\\*/");
		Pattern p = Pattern.compile("/\\*(.*?)\\*/", Pattern.DOTALL);
		Matcher m = p.matcher(fileStr);
		while(m.find()){
			System.out.println(m.group());
		}
	}
	
	public static String getFileStr(String filePathName){
		File file = new File(filePathName);
		FileInputStream fis = null;
		InputStreamReader isr = null;
		StringBuilder subff = new StringBuilder();
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis);
			int tempRead;
			char[] tempChars = new char[100];
			while((tempRead = isr.read(tempChars)) != -1){
				if(tempRead == tempChars.length){
					subff.append(tempChars);
				}else{
					for(int i = 0; i < tempRead; i++){
						subff.append(tempChars[i]);
					}
				}
			}
			isr.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return subff.toString();
	}

}

Scanner使用自定义界定符:

package com.string;

import java.util.Scanner;

public class ScannerTest {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		sc.useDelimiter("\\s*,\\s*");
		while(sc.hasNextInt()){
			int i = sc.nextInt();
			if(i == -1){
				break;
			}
			System.out.println(i);
		}
	}

}


















你可能感兴趣的:(Java进阶之路_重温《java编程思想》篇(六))