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

来源:互联网 发布:最新网络p2p在线理财 编辑:程序博客网 时间:2024/05/21 08:03

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


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


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


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


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


Java IO流的复习


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


呵呵!


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


InputFromConsole

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


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

[java] view plaincopyprint?
  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. }  

ListDir

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

[java] view plaincopyprint?
  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. }  


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


ListMyDirWithSubDir

[java] view plaincopyprint?
  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. }  


InputStreamDemo

从外部读入一个文件


[java] view plaincopyprint?
  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. }  


OutputStreamDemo

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

[java] view plaincopyprint?
  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. }  

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


CopyFile

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

[java] view plaincopyprint?
  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. }  

运行后显示:


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


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

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


BufferInputStreamDemo

[java] view plaincopyprint?
  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. }  
我们Copy同样一个文件,用了多少时间呢?来看!

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


ByteArrayDemo

来看看使用ByteArray输出文件吧

[java] view plaincopyprint?
  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. }  

RandomAccess

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


[java] view plaincopyprint?
  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. }  

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



PipeStream

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


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

SendMessage

[java] view plaincopyprint?
  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. }  

ReceiveMessage

[java] view plaincopyprint?
  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. }  

如何使用这两个类呢?


TestPipeStream

[java] view plaincopyprint?
  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. }  

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


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


Serializable的IO操作


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


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


Person

[java] view plaincopyprint?
  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. }  

下面来看序列化的操作

SerializablePersonToFile

[java] view plaincopyprint?
  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. }  

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


先讲这么些吧!

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

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