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

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


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


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


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


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


Java IO流的复习


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


呵呵!


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


InputFromConsole

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


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

  1. package org.sky.io;  
  2.   
  3. public class InputFromConsole {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) throws Exception {  
  9.         int a = 0;  
  10.         byte[] input = new byte[1024];  
  11.         System.in.read(input);  
  12.         System.out.println("your input is: " + new String(input));  
  13.   
  14.     }  
  15.   
  16. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class ListMyDir {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public static void main(String[] args) {  
  11.         String fileName = "D:" + File.separator + "tomcat2";  
  12.         File f = new File(fileName);  
  13.         File[] fs = f.listFiles();  
  14.         for (int i = 0; i < fs.length; i++) {  
  15.             System.out.println(fs[i].getName());  
  16.         }  
  17.   
  18.     }  
  19.   
  20. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class ListMyDirWithSubDir {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public void print(File f) {  
  11.         if (f != null) {  
  12.             if (f.isDirectory()) {  
  13.                 File[] fileArray = f.listFiles();  
  14.                 if (fileArray != null) {  
  15.                     for (int i = 0; i < fileArray.length; i++) {  
  16.                         print(fileArray[i]);  
  17.                     }  
  18.                 }  
  19.             } else {  
  20.                 System.out.println(f);  
  21.             }  
  22.         }  
  23.     }  
  24.   
  25.     public static void main(String[] args) {  
  26.         String fileName = "D:" + File.separator + "tomcat2";  
  27.         File f = new File(fileName);  
  28.         ListMyDirWithSubDir listDir = new ListMyDirWithSubDir();  
  29.         listDir.print(f);  
  30.   
  31.     }  
  32. }  
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. package org.sky.io;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. public class InputStreamDemo {  
  10.     public void readFile(String fileName) {  
  11.         File srcFile = new File(fileName);  
  12.         InputStream in = null;  
  13.         try {  
  14.             in = new FileInputStream(srcFile);  
  15.             byte[] b = new byte[(int) srcFile.length()];  
  16.             for (int i = 0; i < b.length; i++) {  
  17.                 b[i] = (byte) in.read();  
  18.             }  
  19.             System.out.println(new String(b));  
  20.         } catch (Exception e) {  
  21.             e.printStackTrace();  
  22.         } finally {  
  23.             try {  
  24.                 if (in != null) {  
  25.                     in.close();  
  26.                     in = null;  
  27.                 }  
  28.             } catch (Exception e) {  
  29.             }  
  30.         }  
  31.     }  
  32.   
  33.     public static void main(String[] args) {  
  34.         InputStreamDemo id = new InputStreamDemo();  
  35.         String src = "D:" + File.separator + "hello.txt";  
  36.         id.readFile(src);  
  37.     }  
  38.   
  39. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class OutputStreamDemo {  
  6.   
  7.     public void writeWithByte() {  
  8.         String fileName = "D:" + File.separator + "hello.txt";  
  9.         OutputStream out = null;  
  10.         File f = new File(fileName);  
  11.         try {  
  12.             out = new FileOutputStream(f, true);  
  13.             String str = "   [Publicity ministry of ShangHai Municipal committee of CPC]";  
  14.             byte[] b = str.getBytes();  
  15.             out.write(b);  
  16.         } catch (Exception e) {  
  17.             e.printStackTrace();  
  18.         } finally {  
  19.             try {  
  20.                 if (out != null) {  
  21.                     out.close();  
  22.                     out = null;  
  23.                 }  
  24.             } catch (Exception e) {  
  25.             }  
  26.         }  
  27.     }  
  28.   
  29.     public void writeWithByteArray() {  
  30.         String fileName = "D:" + File.separator + "hello.txt";  
  31.         OutputStream out = null;  
  32.         File f = new File(fileName);  
  33.         try {  
  34.             out = new FileOutputStream(f, true);  
  35.             String str = "   [hello with byte yi ge ge xie]";  
  36.             byte[] b = str.getBytes();  
  37.             for (int i = 0; i < b.length; i++) {  
  38.                 out.write(b[i]);  
  39.             }  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         } finally {  
  43.             try {  
  44.                 if (out != null) {  
  45.                     out.close();  
  46.                     out = null;  
  47.                 }  
  48.             } catch (Exception e) {  
  49.             }  
  50.         }  
  51.     }  
  52.   
  53.     public static void main(String[] args) {  
  54.         OutputStreamDemo od = new OutputStreamDemo();  
  55.         od.writeWithByte();  
  56.         od.writeWithByteArray();  
  57.   
  58.     }  
  59.   
  60. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class CopyFile {  
  6.   
  7.     public void copy(String src, String des) {  
  8.         File srcFile = new File(src);  
  9.         File desFile = new File(des);  
  10.         InputStream in = null;  
  11.         OutputStream out = null;  
  12.         try {  
  13.             in = new FileInputStream(srcFile);  
  14.             out = new FileOutputStream(desFile);  
  15.             byte[] b = new byte[(int) srcFile.length()];  
  16.             for (int i = 0; i < b.length; i++) {  
  17.                 b[i] = (byte) in.read();  
  18.             }  
  19.             out.write(b);  
  20.             System.out.println("copied [" + srcFile.getName() + "]    with    "  
  21.                     + srcFile.length());  
  22.         } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         } finally {  
  25.             try {  
  26.                 if (out != null) {  
  27.                     out.close();  
  28.                     out = null;  
  29.                 }  
  30.             } catch (Exception e) {  
  31.             }  
  32.             try {  
  33.                 if (in != null) {  
  34.                     in.close();  
  35.                     in = null;  
  36.                 }  
  37.             } catch (Exception e) {  
  38.             }  
  39.         }  
  40.     }  
  41.   
  42.     public static void main(String[] args) {  
  43.         CopyFile cp = new CopyFile();  
  44.         String src = "D:" + File.separator + "UltraEdit.zip";  
  45.         String des = "D:" + File.separator + "UltraEdit_Copy.zip";  
  46.         long sTime = System.currentTimeMillis();  
  47.         cp.copy(src, des);  
  48.         long eTime = System.currentTimeMillis();  
  49.         System.out.println("Total spend: " + (eTime - sTime));  
  50.     }  
  51.   
  52. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class BufferInputStreamDemo {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public void copy(String src, String des) {  
  11.         File srcFile = new File(src);  
  12.         File desFile = new File(des);  
  13.         BufferedInputStream bin = null;  
  14.         BufferedOutputStream bout = null;  
  15.         try {  
  16.             bin = new BufferedInputStream(new FileInputStream(srcFile));  
  17.             bout = new BufferedOutputStream(new FileOutputStream(desFile));  
  18.             byte[] b = new byte[1024];  
  19.             while (bin.read(b) != -1) {  
  20.                 bout.write(b);  
  21.             }  
  22.             bout.flush();  
  23.             System.out.println("copied [" + srcFile.getName() + "]    with    "  
  24.                     + srcFile.length());  
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         } finally {  
  28.             try {  
  29.                 if (bout != null) {  
  30.                     bout.close();  
  31.                     bout = null;  
  32.                 }  
  33.             } catch (Exception e) {  
  34.             }  
  35.             try {  
  36.                 if (bin != null) {  
  37.                     bin.close();  
  38.                     bin = null;  
  39.                 }  
  40.             } catch (Exception e) {  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45.     public static void main(String[] args) {  
  46.         BufferInputStreamDemo bd = new BufferInputStreamDemo();  
  47.         String src = "D:" + File.separator + "UltraEdit.zip";  
  48.         String des = "D:" + File.separator + "UltraEdit_Copy.zip";  
  49.         long sTime = System.currentTimeMillis();  
  50.         bd.copy(src, des);  
  51.         long eTime = System.currentTimeMillis();  
  52.         System.out.println("Total spend: " + (eTime - sTime));  
  53.   
  54.     }  
  55.   
  56. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class ByteArrayDemo {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public void testByteArray() {  
  11.         String str = "HOLLYJESUS";  
  12.         ByteArrayInputStream input = null;  
  13.         ByteArrayOutputStream output = null;  
  14.         try {  
  15.             input = new ByteArrayInputStream(str.getBytes());  
  16.             output = new ByteArrayOutputStream();  
  17.             int temp = 0;  
  18.             while ((temp = input.read()) != -1) {  
  19.                 char ch = (char) temp;  
  20.                 output.write(Character.toLowerCase(ch));  
  21.             }  
  22.             String outStr = output.toString();  
  23.             input.close();  
  24.             output.close();  
  25.             System.out.println(outStr);  
  26.         } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         } finally {  
  29.             try {  
  30.                 if (output != null) {  
  31.                     output.close();  
  32.                     output = null;  
  33.                 }  
  34.             } catch (Exception e) {  
  35.             }  
  36.             try {  
  37.                 if (input != null) {  
  38.                     input.close();  
  39.                     input = null;  
  40.                 }  
  41.             } catch (Exception e) {  
  42.             }  
  43.         }  
  44.     }  
  45.   
  46.     public static void main(String[] args) {  
  47.         ByteArrayDemo bd = new ByteArrayDemo();  
  48.         bd.testByteArray();  
  49.   
  50.     }  
  51.   
  52. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class RandomAccess {  
  6.     public void writeToFile() {  
  7.         String fileName = "D:" + File.separator + "hello.txt";  
  8.         RandomAccessFile randomIO = null;  
  9.         try {  
  10.   
  11.             File f = new File(fileName);  
  12.             randomIO = new RandomAccessFile(f, "rw");  
  13.             randomIO.writeBytes("asdsad");  
  14.             randomIO.writeInt(12);  
  15.             randomIO.writeBoolean(true);  
  16.             randomIO.writeChar('A');  
  17.             randomIO.writeFloat(1.21f);  
  18.             randomIO.writeDouble(12.123);  
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         } finally {  
  22.             try {  
  23.                 if (randomIO != null) {  
  24.                     randomIO.close();  
  25.                     randomIO = null;  
  26.                 }  
  27.             } catch (Exception e) {  
  28.             }  
  29.         }  
  30.     }  
  31.   
  32.     public static void main(String[] args) {  
  33.         RandomAccess randomA = new RandomAccess();  
  34.         randomA.writeToFile();  
  35.     }  
  36. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class SendMessage implements Runnable {  
  6.     private PipedOutputStream out = null;  
  7.   
  8.     public PipedOutputStream getOut() {  
  9.         return this.out;  
  10.     }  
  11.   
  12.     public SendMessage() {  
  13.         this.out = new PipedOutputStream();  
  14.     }  
  15.   
  16.     public void send() {  
  17.   
  18.         String msg = "start";  
  19.         try {  
  20.             out.write(msg.getBytes());  
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.         } finally {  
  24.             try {  
  25.                 if (out != null) {  
  26.                     out.close();  
  27.                     out = null;  
  28.                 }  
  29.             } catch (Exception e) {  
  30.             }  
  31.         }  
  32.     }  
  33.   
  34.     public void run() {  
  35.         try {  
  36.             System.out.println("waiting for signal...");  
  37.             Thread.sleep(2000);  
  38.             send();  
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.     }  
  43. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class ReceiveMessage implements Runnable {  
  6.     private PipedInputStream input = null;  
  7.   
  8.     public PipedInputStream getInput() {  
  9.         return this.input;  
  10.     }  
  11.   
  12.     public ReceiveMessage() {  
  13.         this.input = new PipedInputStream();  
  14.     }  
  15.   
  16.     private void receive() {  
  17.   
  18.         byte[] b = new byte[1000];  
  19.         int len = 0;  
  20.         String msg = "";  
  21.         try {  
  22.             len = input.read(b);  
  23.             msg = new String(b, 0, len);  
  24.             if (msg.equals("start")) {  
  25.                 System.out  
  26.                         .println("received the start message, receive now can do something......");  
  27.                 Thread.interrupted();  
  28.             }  
  29.         } catch (Exception e) {  
  30.             e.printStackTrace();  
  31.         } finally {  
  32.             try {  
  33.                 if (input != null) {  
  34.                     input.close();  
  35.                     input = null;  
  36.                 }  
  37.             } catch (Exception e) {  
  38.             }  
  39.         }  
  40.     }  
  41.   
  42.     public void run() {  
  43.         try {  
  44.             receive();  
  45.         } catch (Exception e) {  
  46.         }  
  47.     }  
  48. }  
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. package org.sky.io;  
  2.   
  3. public class TestPipeStream {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         SendMessage send = new SendMessage();  
  10.         ReceiveMessage receive = new ReceiveMessage();  
  11.         try {  
  12.             send.getOut().connect(receive.getInput());  
  13.             Thread t1 = new Thread(send);  
  14.             Thread t2 = new Thread(receive);  
  15.             t1.start();  
  16.             t2.start();  
  17.   
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.   
  22.     }  
  23.   
  24. }  
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. package org.sky.io;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Person implements Serializable {  
  6.   
  7.     private String name = "";  
  8.     private String age = "";  
  9.     private String personId = "";  
  10.   
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.   
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public String getAge() {  
  20.         return age;  
  21.     }  
  22.   
  23.     public void setAge(String age) {  
  24.         this.age = age;  
  25.     }  
  26.   
  27.     public String getPersonId() {  
  28.         return personId;  
  29.     }  
  30.   
  31.     public void setPersonId(String personId) {  
  32.         this.personId = personId;  
  33.     }  
  34.   
  35.     public String getCellPhoneNo() {  
  36.         return cellPhoneNo;  
  37.     }  
  38.   
  39.     public void setCellPhoneNo(String cellPhoneNo) {  
  40.         this.cellPhoneNo = cellPhoneNo;  
  41.     }  
  42.   
  43.     private String cellPhoneNo = "";  
  44. }  
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. package org.sky.io;  
  2.   
  3. import java.io.*;  
  4. import java.util.*;  
  5.   
  6. public class SerializablePersonToFile {  
  7.   
  8.     /** 
  9.      * @param args 
  10.      */  
  11.     private List<Person> initList() {  
  12.         List<Person> userList = new ArrayList<Person>();  
  13.         Person loginUser = new Person();  
  14.         loginUser.setName("sam");  
  15.         loginUser.setAge("30");  
  16.         loginUser.setCellPhoneNo("13333333333");  
  17.         loginUser.setPersonId("111111111111111111");  
  18.         userList.add(loginUser);  
  19.         loginUser = new Person();  
  20.         loginUser.setName("tonny");  
  21.         loginUser.setAge("31");  
  22.         loginUser.setCellPhoneNo("14333333333");  
  23.         loginUser.setPersonId("111111111111111111");  
  24.         userList.add(loginUser);  
  25.         loginUser = new Person();  
  26.         loginUser.setName("jim");  
  27.         loginUser.setAge("28");  
  28.         loginUser.setCellPhoneNo("15333333333");  
  29.         loginUser.setPersonId("111111111111111111");  
  30.         userList.add(loginUser);  
  31.         loginUser = new Person();  
  32.         loginUser.setName("Simon");  
  33.         loginUser.setAge("30");  
  34.         loginUser.setCellPhoneNo("17333333333");  
  35.         loginUser.setPersonId("111111111111111111");  
  36.         userList.add(loginUser);  
  37.         return userList;  
  38.     }  
  39.   
  40.     private  void serializeFromFile() {  
  41.         FileInputStream fs = null;  
  42.         ObjectInputStream ois = null;  
  43.         try {  
  44.             fs = new FileInputStream("person.txt");  
  45.             ois = new ObjectInputStream(fs);  
  46.             List<Person> userList = (ArrayList<Person>) ois.readObject();  
  47.             for (Person p : userList) {  
  48.                 System.out.println(p.getName() + "   " + p.getAge() + "   "  
  49.                         + p.getCellPhoneNo() + "   " + p.getCellPhoneNo());  
  50.             }  
  51.         } catch (Exception ex) {  
  52.             ex.printStackTrace();  
  53.         } finally {  
  54.             try {  
  55.                 if (ois != null) {  
  56.                     ois.close();  
  57.                 }  
  58.             } catch (Exception e) {  
  59.             }  
  60.             try {  
  61.                 if (fs != null) {  
  62.                     fs.close();  
  63.                 }  
  64.             } catch (Exception e) {  
  65.             }  
  66.         }  
  67.     }  
  68.   
  69.     private void serializeToFile() {  
  70.         List<Person> userList = new ArrayList<Person>();  
  71.         userList = initList();  
  72.         FileOutputStream fs = null;  
  73.         ObjectOutputStream os = null;  
  74.         try {  
  75.             fs = new FileOutputStream("person.txt");  
  76.             os = new ObjectOutputStream(fs);  
  77.             os.writeObject(userList);  
  78.         } catch (Exception ex) {  
  79.             ex.printStackTrace();  
  80.         } finally {  
  81.             try {  
  82.                 if (os != null) {  
  83.                     os.close();  
  84.                 }  
  85.             } catch (Exception e) {  
  86.             }  
  87.             try {  
  88.                 if (fs != null) {  
  89.                     fs.close();  
  90.                 }  
  91.             } catch (Exception e) {  
  92.             }  
  93.         }  
  94.     }  
  95.   
  96.     public static void main(String[] args) {  
  97.         SerializablePersonToFile sf = new SerializablePersonToFile();  
  98.         sf.serializeToFile();  
  99.         sf.serializeFromFile();  
  100.     }  
  101.   
  102. }  
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

<think>好的,用户需要2024年版的Java面试资料或宝典。首先,我得确认目前最新的资源是什么。虽然2024年的可能还没完全出来,但可以推荐最近更新的或者经典持续更新的资料。 用户提到的引用里有数据结构和算法的书籍,比如《Data Structures and Algorithms: Deep Dive Using Java》,这可能是一个好的起点。另外,引用中的网站链接可能有最新的资源,比如GitHub上的中文版最佳网站列表,里面可能有程序员分享的最新面试资料。 接下来,我需要考虑用户可能需要的具体内容。Java面试通常包括核心Java、多线程、集合框架、JVM、设计模式、Spring框架等。此外,算法和数据结构也是重点,比如快速排序、哈希表等。因此,推荐的资料应该涵盖这些方面。 还要注意书籍的版本,是否有2023或2024年的更新版。例如,《Effective Java》第三版虽然发布于2018年,但仍是经典,可能还在推荐列表中。另外,一些在线平台如LeetCode、牛客网会有最新的面试题库,这些也是重要的资源。 用户可能还希望有实战项目或系统设计的内容,所以像《Cracking the Coding Interview》这样的书虽然主要针对算法,但也是必备的。此外,GitHub上的开源项目或指南,如“Java设计模式精讲”可能帮助用户深入理解。 需要检查引用中的资料是否有最新版,或者是否有替代的新资源。例如,引用1提到的书籍是否有2024版,或者是否有类似的更新指南。如果没有,可能需要推荐常青资源,并建议用户关注某些网站或社区获取最新信息。 最后,整理这些资源,分门别类,确保结构清晰,让用户能一步步找到所需资料。同时,提醒用户结合实践和理论,参与刷题和模拟面试,这样准备更充分。</think>### 2024年Java面试资料与宝典推荐 #### 一、经典书籍(持续更新版本) 1. **《Effective Java》第三版** 涵盖Java 8/9/10特性,深入讲解编码规范与设计模式,是面试核心考点[^1]。 2. **《Java编程思想》(Thinking in Java)** 系统讲解Java语法与面向对象思想,适合夯实基础。 3. **《深入理解Java虚拟机》第三版** 详解JVM内存模型、垃圾回收机制,高频面试章节如类加载、性能调优。 #### 二、算法与数据结构专项 1. **《Cracking the Coding Interview》第六版** 包含189道编程题及解法,覆盖快速排序、动态规划等高频考点[^1]。 ```java // 示例:快速排序实现 public void quickSort(int[] arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } ``` 2. **LeetCode与牛客网题库** 2024年新增题型聚焦并发编程(如CompletableFuture)和Java 17特性(如模式匹配)[^2]。 #### 三、系统设计与架构 1. **《Head First设计模式》第二版** 结合Spring框架解读单例、工厂等模式,含实际项目案例分析。 2. **《微服务架构设计模式》** 针对分布式系统面试题,如CAP定理、服务熔断等[^1]。 #### 四、最新实战资源 1. **GitHub开源项目** - **「Java面试指南」仓库**:含2024年大厂真题解析(如Redis缓存穿透解决方案)[^3]。 - **「Spring Boot实战项目集」**:整合Spring Cloud Alibaba与Kubernetes部署方案。 2. **在线课程平台** - **极客时间《Java核心技术面试精讲》**:2024年新增Java 21虚拟线程(Virtual Threads)详解。 #### 五、备考策略 1. **分阶段学习计划** - 第一阶段:2周通读《Effective Java》核心章节(如泛型、Lambda) - 第二阶段:3周刷LeetCode Hot 100 + 牛客网Java专项 - 第三阶段:1周模拟面试(使用Pramp或AlgoExpert平台) 2. **避坑指南** - 避免过度关注冷门语法(如Java Flight Recorder),优先掌握高频考点(如HashMap扩容机制) - 警惕过时资料中已被废弃的技术(如Java EE中的Corba)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值