think in java interview-高级开发人员面试宝典(八)

面经出了7套,收到许多读者的Email,有许多人说了,这些基础知识是不是为了后面进一步的”通向架构师的道路“做准备的?


对的,你们没有猜错,就是这样的,我一直在酝酿后面的”通向架构师的道路“如何开章。


说实话,我已经在肚子里准备好的后面的”通向架构师的道路“的内容自己觉得如果一下子全拿出来的话,很多人吃不消,因为架构越来越复杂,用到的知识越来越多,而且很多都是各知识点的混合应用。


所以,先以这几套面经来铺路,我们把基础打实了,才能把大楼造的更好。因为,一个架构师首先他是一个程序员,他的基础知识必须非常的扎实,API对于架构师来说已经不太需要eclipse的code insight(即在eclipse编辑器里打一个小点点就可以得到后面的函数),尤其是一些常用的JAVA API来说,是必须熟记于心的。


下面我们继续来几天面经,顺带便复习一下JAVA和数据库的一些基础。


Java IO流的复习


大家平时J2EE写多了,JAVA的IO操作可能都已经生疏了,面试时如果来上这么几道,是不是有点”其实这个问题很简单,可是我就是想不起来“的感觉啊?


呵呵!


JAVA的IO操作太多,我这边挑腾迅,盛大和百度的几道面试题,并整理出答案来供大家参考。


InputFromConsole

这个最简单不过了,从console接受用户输入的字符,如和用户有交互的命令行。


如果你不复习的话,嘿嘿,还真答不出,来看:

  1. packageorg.sky.io;
  2. publicclassInputFromConsole{
  3. /**
  4. *@paramargs
  5. */
  6. publicstaticvoidmain(String[]args)throwsException{
  7. inta=0;
  8. byte[]input=newbyte[1024];
  9. System.in.read(input);
  10. System.out.println("yourinputis:"+newString(input));
  11. }
  12. }
package org.sky.io;

public class InputFromConsole {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		int a = 0;
		byte[] input = new byte[1024];
		System.in.read(input);
		System.out.println("your input is: " + new String(input));

	}

}

ListDir

列出给出路径下所有的目录,包括子目录

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassListMyDir{
  4. /**
  5. *@paramargs
  6. */
  7. publicstaticvoidmain(String[]args){
  8. StringfileName="D:"+File.separator+"tomcat2";
  9. Filef=newFile(fileName);
  10. File[]fs=f.listFiles();
  11. for(inti=0;i<fs.length;i++){
  12. System.out.println(fs[i].getName());
  13. }
  14. }
  15. }
package org.sky.io;

import java.io.*;

public class ListMyDir {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "tomcat2";
		File f = new File(fileName);
		File[] fs = f.listFiles();
		for (int i = 0; i < fs.length; i++) {
			System.out.println(fs[i].getName());
		}

	}

}


咦,上面这个程序只列出了一层目录,我们想连子目录一起List出来怎么办?


ListMyDirWithSubDir

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassListMyDirWithSubDir{
  4. /**
  5. *@paramargs
  6. */
  7. publicvoidprint(Filef){
  8. if(f!=null){
  9. if(f.isDirectory()){
  10. File[]fileArray=f.listFiles();
  11. if(fileArray!=null){
  12. for(inti=0;i<fileArray.length;i++){
  13. print(fileArray[i]);
  14. }
  15. }
  16. }else{
  17. System.out.println(f);
  18. }
  19. }
  20. }
  21. publicstaticvoidmain(String[]args){
  22. StringfileName="D:"+File.separator+"tomcat2";
  23. Filef=newFile(fileName);
  24. ListMyDirWithSubDirlistDir=newListMyDirWithSubDir();
  25. listDir.print(f);
  26. }
  27. }
package org.sky.io;

import java.io.*;

public class ListMyDirWithSubDir {

	/**
	 * @param args
	 */
	public void print(File f) {
		if (f != null) {
			if (f.isDirectory()) {
				File[] fileArray = f.listFiles();
				if (fileArray != null) {
					for (int i = 0; i < fileArray.length; i++) {
						print(fileArray[i]);
					}
				}
			} else {
				System.out.println(f);
			}
		}
	}

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "tomcat2";
		File f = new File(fileName);
		ListMyDirWithSubDir listDir = new ListMyDirWithSubDir();
		listDir.print(f);

	}
}


InputStreamDemo

从外部读入一个文件


  1. packageorg.sky.io;
  2. importjava.io.File;
  3. importjava.io.FileInputStream;
  4. importjava.io.FileOutputStream;
  5. importjava.io.InputStream;
  6. importjava.io.OutputStream;
  7. publicclassInputStreamDemo{
  8. publicvoidreadFile(StringfileName){
  9. FilesrcFile=newFile(fileName);
  10. InputStreamin=null;
  11. try{
  12. in=newFileInputStream(srcFile);
  13. byte[]b=newbyte[(int)srcFile.length()];
  14. for(inti=0;i<b.length;i++){
  15. b[i]=(byte)in.read();
  16. }
  17. System.out.println(newString(b));
  18. }catch(Exceptione){
  19. e.printStackTrace();
  20. }finally{
  21. try{
  22. if(in!=null){
  23. in.close();
  24. in=null;
  25. }
  26. }catch(Exceptione){
  27. }
  28. }
  29. }
  30. publicstaticvoidmain(String[]args){
  31. InputStreamDemoid=newInputStreamDemo();
  32. Stringsrc="D:"+File.separator+"hello.txt";
  33. id.readFile(src);
  34. }
  35. }
package org.sky.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class InputStreamDemo {
	public void readFile(String fileName) {
		File srcFile = new File(fileName);
		InputStream in = null;
		try {
			in = new FileInputStream(srcFile);
			byte[] b = new byte[(int) srcFile.length()];
			for (int i = 0; i < b.length; i++) {
				b[i] = (byte) in.read();
			}
			System.out.println(new String(b));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		InputStreamDemo id = new InputStreamDemo();
		String src = "D:" + File.separator + "hello.txt";
		id.readFile(src);
	}

}


OutputStreamDemo

讲完了InputStream来讲OutputStream,输出内容至外部的一个文件

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassOutputStreamDemo{
  4. publicvoidwriteWithByte(){
  5. StringfileName="D:"+File.separator+"hello.txt";
  6. OutputStreamout=null;
  7. Filef=newFile(fileName);
  8. try{
  9. out=newFileOutputStream(f,true);
  10. Stringstr="[PublicityministryofShangHaiMunicipalcommitteeofCPC]";
  11. byte[]b=str.getBytes();
  12. out.write(b);
  13. }catch(Exceptione){
  14. e.printStackTrace();
  15. }finally{
  16. try{
  17. if(out!=null){
  18. out.close();
  19. out=null;
  20. }
  21. }catch(Exceptione){
  22. }
  23. }
  24. }
  25. publicvoidwriteWithByteArray(){
  26. StringfileName="D:"+File.separator+"hello.txt";
  27. OutputStreamout=null;
  28. Filef=newFile(fileName);
  29. try{
  30. out=newFileOutputStream(f,true);
  31. Stringstr="[hellowithbyteyigegexie]";
  32. byte[]b=str.getBytes();
  33. for(inti=0;i<b.length;i++){
  34. out.write(b[i]);
  35. }
  36. }catch(Exceptione){
  37. e.printStackTrace();
  38. }finally{
  39. try{
  40. if(out!=null){
  41. out.close();
  42. out=null;
  43. }
  44. }catch(Exceptione){
  45. }
  46. }
  47. }
  48. publicstaticvoidmain(String[]args){
  49. OutputStreamDemood=newOutputStreamDemo();
  50. od.writeWithByte();
  51. od.writeWithByteArray();
  52. }
  53. }
package org.sky.io;

import java.io.*;

public class OutputStreamDemo {

	public void writeWithByte() {
		String fileName = "D:" + File.separator + "hello.txt";
		OutputStream out = null;
		File f = new File(fileName);
		try {
			out = new FileOutputStream(f, true);
			String str = "   [Publicity ministry of ShangHai Municipal committee of CPC]";
			byte[] b = str.getBytes();
			out.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public void writeWithByteArray() {
		String fileName = "D:" + File.separator + "hello.txt";
		OutputStream out = null;
		File f = new File(fileName);
		try {
			out = new FileOutputStream(f, true);
			String str = "   [hello with byte yi ge ge xie]";
			byte[] b = str.getBytes();
			for (int i = 0; i < b.length; i++) {
				out.write(b[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		OutputStreamDemo od = new OutputStreamDemo();
		od.writeWithByte();
		od.writeWithByteArray();

	}

}

这个Demo里分别用了”writeWithByte“和 ”writeWithByteArray“两种方法,注意查看


CopyFile

我们讲完了InputStream和OutputStream,我们就可以自己实现一个File Copy的功能了,来看

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassCopyFile{
  4. publicvoidcopy(Stringsrc,Stringdes){
  5. FilesrcFile=newFile(src);
  6. FiledesFile=newFile(des);
  7. InputStreamin=null;
  8. OutputStreamout=null;
  9. try{
  10. in=newFileInputStream(srcFile);
  11. out=newFileOutputStream(desFile);
  12. byte[]b=newbyte[(int)srcFile.length()];
  13. for(inti=0;i<b.length;i++){
  14. b[i]=(byte)in.read();
  15. }
  16. out.write(b);
  17. System.out.println("copied["+srcFile.getName()+"]with"
  18. +srcFile.length());
  19. }catch(Exceptione){
  20. e.printStackTrace();
  21. }finally{
  22. try{
  23. if(out!=null){
  24. out.close();
  25. out=null;
  26. }
  27. }catch(Exceptione){
  28. }
  29. try{
  30. if(in!=null){
  31. in.close();
  32. in=null;
  33. }
  34. }catch(Exceptione){
  35. }
  36. }
  37. }
  38. publicstaticvoidmain(String[]args){
  39. CopyFilecp=newCopyFile();
  40. Stringsrc="D:"+File.separator+"UltraEdit.zip";
  41. Stringdes="D:"+File.separator+"UltraEdit_Copy.zip";
  42. longsTime=System.currentTimeMillis();
  43. cp.copy(src,des);
  44. longeTime=System.currentTimeMillis();
  45. System.out.println("Totalspend:"+(eTime-sTime));
  46. }
  47. }
package org.sky.io;

import java.io.*;

public class CopyFile {

	public void copy(String src, String des) {
		File srcFile = new File(src);
		File desFile = new File(des);
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(desFile);
			byte[] b = new byte[(int) srcFile.length()];
			for (int i = 0; i < b.length; i++) {
				b[i] = (byte) in.read();
			}
			out.write(b);
			System.out.println("copied [" + srcFile.getName() + "]    with    "
					+ srcFile.length());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
			}
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		CopyFile cp = new CopyFile();
		String src = "D:" + File.separator + "UltraEdit.zip";
		String des = "D:" + File.separator + "UltraEdit_Copy.zip";
		long sTime = System.currentTimeMillis();
		cp.copy(src, des);
		long eTime = System.currentTimeMillis();
		System.out.println("Total spend: " + (eTime - sTime));
	}

}

运行后显示:


来看我们被Copy的这个文件的大小:


也不大,怎么用了7秒多?

原是我们没有使用Buffer这个东西,即缓冲,性能会相差多大呢?来看


BufferInputStreamDemo

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassBufferInputStreamDemo{
  4. /**
  5. *@paramargs
  6. */
  7. publicvoidcopy(Stringsrc,Stringdes){
  8. FilesrcFile=newFile(src);
  9. FiledesFile=newFile(des);
  10. BufferedInputStreambin=null;
  11. BufferedOutputStreambout=null;
  12. try{
  13. bin=newBufferedInputStream(newFileInputStream(srcFile));
  14. bout=newBufferedOutputStream(newFileOutputStream(desFile));
  15. byte[]b=newbyte[1024];
  16. while(bin.read(b)!=-1){
  17. bout.write(b);
  18. }
  19. bout.flush();
  20. System.out.println("copied["+srcFile.getName()+"]with"
  21. +srcFile.length());
  22. }catch(Exceptione){
  23. e.printStackTrace();
  24. }finally{
  25. try{
  26. if(bout!=null){
  27. bout.close();
  28. bout=null;
  29. }
  30. }catch(Exceptione){
  31. }
  32. try{
  33. if(bin!=null){
  34. bin.close();
  35. bin=null;
  36. }
  37. }catch(Exceptione){
  38. }
  39. }
  40. }
  41. publicstaticvoidmain(String[]args){
  42. BufferInputStreamDemobd=newBufferInputStreamDemo();
  43. Stringsrc="D:"+File.separator+"UltraEdit.zip";
  44. Stringdes="D:"+File.separator+"UltraEdit_Copy.zip";
  45. longsTime=System.currentTimeMillis();
  46. bd.copy(src,des);
  47. longeTime=System.currentTimeMillis();
  48. System.out.println("Totalspend:"+(eTime-sTime));
  49. }
  50. }
package org.sky.io;

import java.io.*;

public class BufferInputStreamDemo {

	/**
	 * @param args
	 */
	public void copy(String src, String des) {
		File srcFile = new File(src);
		File desFile = new File(des);
		BufferedInputStream bin = null;
		BufferedOutputStream bout = null;
		try {
			bin = new BufferedInputStream(new FileInputStream(srcFile));
			bout = new BufferedOutputStream(new FileOutputStream(desFile));
			byte[] b = new byte[1024];
			while (bin.read(b) != -1) {
				bout.write(b);
			}
			bout.flush();
			System.out.println("copied [" + srcFile.getName() + "]    with    "
					+ srcFile.length());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bout != null) {
					bout.close();
					bout = null;
				}
			} catch (Exception e) {
			}
			try {
				if (bin != null) {
					bin.close();
					bin = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		BufferInputStreamDemo bd = new BufferInputStreamDemo();
		String src = "D:" + File.separator + "UltraEdit.zip";
		String des = "D:" + File.separator + "UltraEdit_Copy.zip";
		long sTime = System.currentTimeMillis();
		bd.copy(src, des);
		long eTime = System.currentTimeMillis();
		System.out.println("Total spend: " + (eTime - sTime));

	}

}
我们Copy同样一个文件,用了多少时间呢?来看!

丫只用了14毫秒,CALL!!!


ByteArrayDemo

来看看使用ByteArray输出文件吧

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassByteArrayDemo{
  4. /**
  5. *@paramargs
  6. */
  7. publicvoidtestByteArray(){
  8. Stringstr="HOLLYJESUS";
  9. ByteArrayInputStreaminput=null;
  10. ByteArrayOutputStreamoutput=null;
  11. try{
  12. input=newByteArrayInputStream(str.getBytes());
  13. output=newByteArrayOutputStream();
  14. inttemp=0;
  15. while((temp=input.read())!=-1){
  16. charch=(char)temp;
  17. output.write(Character.toLowerCase(ch));
  18. }
  19. StringoutStr=output.toString();
  20. input.close();
  21. output.close();
  22. System.out.println(outStr);
  23. }catch(Exceptione){
  24. e.printStackTrace();
  25. }finally{
  26. try{
  27. if(output!=null){
  28. output.close();
  29. output=null;
  30. }
  31. }catch(Exceptione){
  32. }
  33. try{
  34. if(input!=null){
  35. input.close();
  36. input=null;
  37. }
  38. }catch(Exceptione){
  39. }
  40. }
  41. }
  42. publicstaticvoidmain(String[]args){
  43. ByteArrayDemobd=newByteArrayDemo();
  44. bd.testByteArray();
  45. }
  46. }
package org.sky.io;

import java.io.*;

public class ByteArrayDemo {

	/**
	 * @param args
	 */
	public void testByteArray() {
		String str = "HOLLYJESUS";
		ByteArrayInputStream input = null;
		ByteArrayOutputStream output = null;
		try {
			input = new ByteArrayInputStream(str.getBytes());
			output = new ByteArrayOutputStream();
			int temp = 0;
			while ((temp = input.read()) != -1) {
				char ch = (char) temp;
				output.write(Character.toLowerCase(ch));
			}
			String outStr = output.toString();
			input.close();
			output.close();
			System.out.println(outStr);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
					output = null;
				}
			} catch (Exception e) {
			}
			try {
				if (input != null) {
					input.close();
					input = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		ByteArrayDemo bd = new ByteArrayDemo();
		bd.testByteArray();

	}

}

RandomAccess

有种输出流叫Random,你们还记得吗?学习时记得的,工作久了,HOHO,忘了,它到底有什么特殊的地方呢?来看:


  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassRandomAccess{
  4. publicvoidwriteToFile(){
  5. StringfileName="D:"+File.separator+"hello.txt";
  6. RandomAccessFilerandomIO=null;
  7. try{
  8. Filef=newFile(fileName);
  9. randomIO=newRandomAccessFile(f,"rw");
  10. randomIO.writeBytes("asdsad");
  11. randomIO.writeInt(12);
  12. randomIO.writeBoolean(true);
  13. randomIO.writeChar('A');
  14. randomIO.writeFloat(1.21f);
  15. randomIO.writeDouble(12.123);
  16. }catch(Exceptione){
  17. e.printStackTrace();
  18. }finally{
  19. try{
  20. if(randomIO!=null){
  21. randomIO.close();
  22. randomIO=null;
  23. }
  24. }catch(Exceptione){
  25. }
  26. }
  27. }
  28. publicstaticvoidmain(String[]args){
  29. RandomAccessrandomA=newRandomAccess();
  30. randomA.writeToFile();
  31. }
  32. }
package org.sky.io;

import java.io.*;

public class RandomAccess {
	public void writeToFile() {
		String fileName = "D:" + File.separator + "hello.txt";
		RandomAccessFile randomIO = null;
		try {

			File f = new File(fileName);
			randomIO = new RandomAccessFile(f, "rw");
			randomIO.writeBytes("asdsad");
			randomIO.writeInt(12);
			randomIO.writeBoolean(true);
			randomIO.writeChar('A');
			randomIO.writeFloat(1.21f);
			randomIO.writeDouble(12.123);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (randomIO != null) {
					randomIO.close();
					randomIO = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		RandomAccess randomA = new RandomAccess();
		randomA.writeToFile();
	}
}

它输出后的文件是怎么样的呢?



PipeStream

这个流很特殊,我们在线程操作时,两个线程都在运行,这时通过发送一个指令让某个线程do something,我们在以前的jdk1.4中为了实现这样的功能,使用的就是这个PipeStream


先来看两个类,一个叫SendMessage,即发送一个指令。一个叫ReceiveMessage,用于接受指令。

SendMessage

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassSendMessageimplementsRunnable{
  4. privatePipedOutputStreamout=null;
  5. publicPipedOutputStreamgetOut(){
  6. returnthis.out;
  7. }
  8. publicSendMessage(){
  9. this.out=newPipedOutputStream();
  10. }
  11. publicvoidsend(){
  12. Stringmsg="start";
  13. try{
  14. out.write(msg.getBytes());
  15. }catch(Exceptione){
  16. e.printStackTrace();
  17. }finally{
  18. try{
  19. if(out!=null){
  20. out.close();
  21. out=null;
  22. }
  23. }catch(Exceptione){
  24. }
  25. }
  26. }
  27. publicvoidrun(){
  28. try{
  29. System.out.println("waitingforsignal...");
  30. Thread.sleep(2000);
  31. send();
  32. }catch(Exceptione){
  33. e.printStackTrace();
  34. }
  35. }
  36. }
package org.sky.io;

import java.io.*;

public class SendMessage implements Runnable {
	private PipedOutputStream out = null;

	public PipedOutputStream getOut() {
		return this.out;
	}

	public SendMessage() {
		this.out = new PipedOutputStream();
	}

	public void send() {

		String msg = "start";
		try {
			out.write(msg.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public void run() {
		try {
			System.out.println("waiting for signal...");
			Thread.sleep(2000);
			send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ReceiveMessage

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. publicclassReceiveMessageimplementsRunnable{
  4. privatePipedInputStreaminput=null;
  5. publicPipedInputStreamgetInput(){
  6. returnthis.input;
  7. }
  8. publicReceiveMessage(){
  9. this.input=newPipedInputStream();
  10. }
  11. privatevoidreceive(){
  12. byte[]b=newbyte[1000];
  13. intlen=0;
  14. Stringmsg="";
  15. try{
  16. len=input.read(b);
  17. msg=newString(b,0,len);
  18. if(msg.equals("start")){
  19. System.out
  20. .println("receivedthestartmessage,receivenowcandosomething......");
  21. Thread.interrupted();
  22. }
  23. }catch(Exceptione){
  24. e.printStackTrace();
  25. }finally{
  26. try{
  27. if(input!=null){
  28. input.close();
  29. input=null;
  30. }
  31. }catch(Exceptione){
  32. }
  33. }
  34. }
  35. publicvoidrun(){
  36. try{
  37. receive();
  38. }catch(Exceptione){
  39. }
  40. }
  41. }
package org.sky.io;

import java.io.*;

public class ReceiveMessage implements Runnable {
	private PipedInputStream input = null;

	public PipedInputStream getInput() {
		return this.input;
	}

	public ReceiveMessage() {
		this.input = new PipedInputStream();
	}

	private void receive() {

		byte[] b = new byte[1000];
		int len = 0;
		String msg = "";
		try {
			len = input.read(b);
			msg = new String(b, 0, len);
			if (msg.equals("start")) {
				System.out
						.println("received the start message, receive now can do something......");
				Thread.interrupted();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
					input = null;
				}
			} catch (Exception e) {
			}
		}
	}

	public void run() {
		try {
			receive();
		} catch (Exception e) {
		}
	}
}

如何使用这两个类呢?


TestPipeStream

  1. packageorg.sky.io;
  2. publicclassTestPipeStream{
  3. /**
  4. *@paramargs
  5. */
  6. publicstaticvoidmain(String[]args){
  7. SendMessagesend=newSendMessage();
  8. ReceiveMessagereceive=newReceiveMessage();
  9. try{
  10. send.getOut().connect(receive.getInput());
  11. Threadt1=newThread(send);
  12. Threadt2=newThread(receive);
  13. t1.start();
  14. t2.start();
  15. }catch(Exceptione){
  16. e.printStackTrace();
  17. }
  18. }
  19. }
package org.sky.io;

public class TestPipeStream {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SendMessage send = new SendMessage();
		ReceiveMessage receive = new ReceiveMessage();
		try {
			send.getOut().connect(receive.getInput());
			Thread t1 = new Thread(send);
			Thread t2 = new Thread(receive);
			t1.start();
			t2.start();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

注意这边有一个send.getOut().connect(receive.getInput());


这个方法就把两个线程”connect“起来了。


Serializable的IO操作


把一个类序列化到磁盘上,怎么做?


先来看我们要序列化的一个Java Bean


Person

  1. packageorg.sky.io;
  2. importjava.io.Serializable;
  3. publicclassPersonimplementsSerializable{
  4. privateStringname="";
  5. privateStringage="";
  6. privateStringpersonId="";
  7. publicStringgetName(){
  8. returnname;
  9. }
  10. publicvoidsetName(Stringname){
  11. this.name=name;
  12. }
  13. publicStringgetAge(){
  14. returnage;
  15. }
  16. publicvoidsetAge(Stringage){
  17. this.age=age;
  18. }
  19. publicStringgetPersonId(){
  20. returnpersonId;
  21. }
  22. publicvoidsetPersonId(StringpersonId){
  23. this.personId=personId;
  24. }
  25. publicStringgetCellPhoneNo(){
  26. returncellPhoneNo;
  27. }
  28. publicvoidsetCellPhoneNo(StringcellPhoneNo){
  29. this.cellPhoneNo=cellPhoneNo;
  30. }
  31. privateStringcellPhoneNo="";
  32. }
package org.sky.io;

import java.io.Serializable;

public class Person implements Serializable {

	private String name = "";
	private String age = "";
	private String personId = "";

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getPersonId() {
		return personId;
	}

	public void setPersonId(String personId) {
		this.personId = personId;
	}

	public String getCellPhoneNo() {
		return cellPhoneNo;
	}

	public void setCellPhoneNo(String cellPhoneNo) {
		this.cellPhoneNo = cellPhoneNo;
	}

	private String cellPhoneNo = "";
}

下面来看序列化的操作

SerializablePersonToFile

  1. packageorg.sky.io;
  2. importjava.io.*;
  3. importjava.util.*;
  4. publicclassSerializablePersonToFile{
  5. /**
  6. *@paramargs
  7. */
  8. privateList<Person>initList(){
  9. List<Person>userList=newArrayList<Person>();
  10. PersonloginUser=newPerson();
  11. loginUser.setName("sam");
  12. loginUser.setAge("30");
  13. loginUser.setCellPhoneNo("13333333333");
  14. loginUser.setPersonId("111111111111111111");
  15. userList.add(loginUser);
  16. loginUser=newPerson();
  17. loginUser.setName("tonny");
  18. loginUser.setAge("31");
  19. loginUser.setCellPhoneNo("14333333333");
  20. loginUser.setPersonId("111111111111111111");
  21. userList.add(loginUser);
  22. loginUser=newPerson();
  23. loginUser.setName("jim");
  24. loginUser.setAge("28");
  25. loginUser.setCellPhoneNo("15333333333");
  26. loginUser.setPersonId("111111111111111111");
  27. userList.add(loginUser);
  28. loginUser=newPerson();
  29. loginUser.setName("Simon");
  30. loginUser.setAge("30");
  31. loginUser.setCellPhoneNo("17333333333");
  32. loginUser.setPersonId("111111111111111111");
  33. userList.add(loginUser);
  34. returnuserList;
  35. }
  36. privatevoidserializeFromFile(){
  37. FileInputStreamfs=null;
  38. ObjectInputStreamois=null;
  39. try{
  40. fs=newFileInputStream("person.txt");
  41. ois=newObjectInputStream(fs);
  42. List<Person>userList=(ArrayList<Person>)ois.readObject();
  43. for(Personp:userList){
  44. System.out.println(p.getName()+""+p.getAge()+""
  45. +p.getCellPhoneNo()+""+p.getCellPhoneNo());
  46. }
  47. }catch(Exceptionex){
  48. ex.printStackTrace();
  49. }finally{
  50. try{
  51. if(ois!=null){
  52. ois.close();
  53. }
  54. }catch(Exceptione){
  55. }
  56. try{
  57. if(fs!=null){
  58. fs.close();
  59. }
  60. }catch(Exceptione){
  61. }
  62. }
  63. }
  64. privatevoidserializeToFile(){
  65. List<Person>userList=newArrayList<Person>();
  66. userList=initList();
  67. FileOutputStreamfs=null;
  68. ObjectOutputStreamos=null;
  69. try{
  70. fs=newFileOutputStream("person.txt");
  71. os=newObjectOutputStream(fs);
  72. os.writeObject(userList);
  73. }catch(Exceptionex){
  74. ex.printStackTrace();
  75. }finally{
  76. try{
  77. if(os!=null){
  78. os.close();
  79. }
  80. }catch(Exceptione){
  81. }
  82. try{
  83. if(fs!=null){
  84. fs.close();
  85. }
  86. }catch(Exceptione){
  87. }
  88. }
  89. }
  90. publicstaticvoidmain(String[]args){
  91. SerializablePersonToFilesf=newSerializablePersonToFile();
  92. sf.serializeToFile();
  93. sf.serializeFromFile();
  94. }
  95. }
package org.sky.io;

import java.io.*;
import java.util.*;

public class SerializablePersonToFile {

	/**
	 * @param args
	 */
	private List<Person> initList() {
		List<Person> userList = new ArrayList<Person>();
		Person loginUser = new Person();
		loginUser.setName("sam");
		loginUser.setAge("30");
		loginUser.setCellPhoneNo("13333333333");
		loginUser.setPersonId("111111111111111111");
		userList.add(loginUser);
		loginUser = new Person();
		loginUser.setName("tonny");
		loginUser.setAge("31");
		loginUser.setCellPhoneNo("14333333333");
		loginUser.setPersonId("111111111111111111");
		userList.add(loginUser);
		loginUser = new Person();
		loginUser.setName("jim");
		loginUser.setAge("28");
		loginUser.setCellPhoneNo("15333333333");
		loginUser.setPersonId("111111111111111111");
		userList.add(loginUser);
		loginUser = new Person();
		loginUser.setName("Simon");
		loginUser.setAge("30");
		loginUser.setCellPhoneNo("17333333333");
		loginUser.setPersonId("111111111111111111");
		userList.add(loginUser);
		return userList;
	}

	private  void serializeFromFile() {
		FileInputStream fs = null;
		ObjectInputStream ois = null;
		try {
			fs = new FileInputStream("person.txt");
			ois = new ObjectInputStream(fs);
			List<Person> userList = (ArrayList<Person>) ois.readObject();
			for (Person p : userList) {
				System.out.println(p.getName() + "   " + p.getAge() + "   "
						+ p.getCellPhoneNo() + "   " + p.getCellPhoneNo());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
			} catch (Exception e) {
			}
			try {
				if (fs != null) {
					fs.close();
				}
			} catch (Exception e) {
			}
		}
	}

	private void serializeToFile() {
		List<Person> userList = new ArrayList<Person>();
		userList = initList();
		FileOutputStream fs = null;
		ObjectOutputStream os = null;
		try {
			fs = new FileOutputStream("person.txt");
			os = new ObjectOutputStream(fs);
			os.writeObject(userList);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (Exception e) {
			}
			try {
				if (fs != null) {
					fs.close();
				}
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {
		SerializablePersonToFile sf = new SerializablePersonToFile();
		sf.serializeToFile();
		sf.serializeFromFile();
	}

}

这边先把Person输出到Person.txt,再从Person.txt里反序列化出这个Person的Java Bean。


先讲这么些吧!

Java的流操作还有很多,这些是经常会被面试到的,很基础,因此经常被考到。

以前听一个读IT的同学说过,这些IO操作,就算没有Eclipse编辑器的话,用文本编辑器也应该能够写出来,你写不出只能代表你的基础太弱了。

转载地址:http://blog.youkuaiyun.com/lifetragedy/article/details/10363489

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值