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

Java工程师面试宝典(重要) 第一阶段面试题 一、JAVA基础 1. 列出JAVA中所有基本数据类型,并说明这些数据类型占用的字节数?? 答案: java的原始数据类型,也可以叫java的基本数据类型,一共就8个,分别是:byte、short、int、long、boolean、char、float、double byte 1个字节 boolean 1个字节 char 2个字节 short 2个字节 int 4... 阅读详情

面经出了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

2019年蚂蚁课堂-余胜军主编Java工程师面试宝典-V1.0.pdf 2019年蚂蚁课堂-余胜军主编Java工程师面试宝典,每特教育培训总结面试,高薪宝典 立即下载

相关推荐

2018年蚂蚁课堂_每特教育_Java工程师面试宝典(余胜军)-V1.0.pdf

97后IT天才余胜军所编写,经过1000余开发者成功验证,顺利找到高薪工作。文档几乎涵盖了高级开发所涉及到的知识点!!!

面试题汇总

自整理面经

weixin_41569825的博客 1081

2019年蚂蚁课堂-余胜军主编Java工程师面试宝典-V1.0

2019年蚂蚁课堂-余胜军主编Java工程师面试宝典-V1.0

2022最新发布史上最强的《Java岗面试宝典》PDF版,拿走不谢

由于细节内容实在是太多了,只能把部分知识点里面的章节挑出来介绍一下,每个章节的小节点里面都有更详细的内容!以下就是部分知识点的目录,由于平台的篇幅限制原因,子节点上的详细讲解也无法全部展示,文末有货取以下章节的所有详细知识讲解。能这么快拿下多个大厂 offer 这全得益于一份堪称神级的 Java 面试宝典,非常不错 面试干货很多。小编也是本着雷锋精神在此分享出来,希望能帮助到更多的朋友。服务跟踪(starter-sleuth)服务熔断(Hystrix)基于 Redis 分布式锁。Netty RPC 实现。

aa119101的博客 3230

2019年蚂蚁课堂-余胜军主编Java工程师面试宝典-V1.0.pdf.zip

每特学院的面试宝典,还不错,希望对新手有帮助,2019年版

Java初中级程序员面试宝典

Java初中级程序员面试宝典 ①熟悉Java基础、面向对象、JVM、IO流程、多线程、集合框架 ②熟悉JSP、Servlet、Spring、Hibernate、Mybatis、SpringMVC ③熟悉Http协议、Socket、WebService及网络编程 ④熟悉Maven及Linux常用命令 ⑤设计模式与算法、JVM. ⑤项目相关知识

JAVA高级工程师面试宝典——数据库方面(七)

七、数据库方面 1.mysql查询字段区不区分大小写? 答:不区分,哪怕值也不区分 2.简单说说数据库集群和负载均衡、分布式 答: 3.存储过程的结构和优点 答:结构createprocproc_find_stu(@startIdint, @endIdint)as select*fromstudent whereid between@...

南山浪子的专栏 872

FPGA新手必看:Create HDL Wrapper和Generating Output Products到底该先用哪个?

本文深入解析了FPGA设计中Create HDL Wrapper与Generating Output Products的正确使用顺序,帮助新手避免常见错误。详细介绍了两者的功能差异、执行顺序的底层逻辑以及工程管理的最佳实践,特别适合使用Vivado进行FPGA开发的初学者。

xk7n92h3p5m的博客 1062

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

面经出了7套,收到许多读者的Email,有许多人说了,这些基础知识是不是为了后面进一步的”通向架构师的道路“做准备的?   对的,你们没有猜错,就是这样的,我一直在酝酿后面的”通向架构师的道路“如何开章。   说实话,我已经在肚子里准备好的后面的”通向架构师的道路“的内容自己觉得如果一下子全拿出来的话,很多人吃不消,因为架构越来越复杂,用到的知识越来越多,而且很多都是各知识点的混合应用。 ...

weixin_34367845的博客 116

模拟IC版图DRC实战:手把手教你搞定MIM电容天线错误和ESD.10g违例

本文深入解析模拟IC版图中的MIM电容天线错误和ESD.10g违例问题,提供从错误解码到实战修复的完整指南。通过电路图修改、版图优化和验证闭环等步骤,帮助工程师高效解决DRC错误,特别适用于ADC等精密模拟电路设计。文章还分享了高级排错技巧和预防性设计策略,大幅提升流片成功率。

weixin_27697385的博客 293

Wireshark抓包分析:如何从HTTP流量中快速定位黑客攻击痕迹(附pcap文件)

本文通过Wireshark实战,详细解析了如何从HTTP流量中快速定位黑客攻击痕迹。文章提供了核心过滤策略,并重点剖析了如何识别SQL注入攻击的流量特征、揭露WebShell的隐蔽通信以及追踪攻击者在横向移动中的行为,帮助安全人员系统性地从pcap文件中还原完整攻击链。

sprite的博客 1008

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

无论你是在职,非在职,高级工程师,工程师,架构师,如果你正在面试阶段,请看完此文,相信这篇文章对你的职业生涯和阶值观会发生重大的改变。如果你是一名PM或者是管理者正在物色合适的开发人选,那么我相信这篇文章会在在如何挑选技术型人材上给你带来重大的帮助。作为一名技术型人材由期是程序员,用什么可以恒量自己是否合格或者我们怎么去恒量一个程序员是否质深,比如说:他可以适合一般的软件工程师岗位,还是适合高级工

打造全国最全的AI Agent开发知识领域的博客 2万+

AES攻击方法 :差分密码分析 boomerang attack飞去来器攻击

AES具有123比特的分组长度,三种可选的密钥长度(128,192,256) AES是一个迭代型密码,轮数依赖于密钥长度。如果密钥长度为128比特,则轮数为10;如果密钥长度为192比特,则轮数为12;如果密钥长度为256比特,则轮数为14; 混淆(Confusion) 混淆是为了让密钥与密文的统计信息之间的关系变得复杂,从而增加通过统计方法进行攻击的难度。混淆可以通过各种代换算法实现,如S盒、乘法(加)与异或等运算组合,为非线性部件。 扩散(Diffusion) 扩散是为了让明文的单个比特影像到

m0_67105022的博客 3491

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

模拟面试今天来谈一下面试时的综合能力。下面先来看一份简历的摘要。熟练掌握SPRING, STRUTS1, 2, HIBERNATE;J2EE方面5年工作经验;ORACLE使用经验48个月;熟练掌握JAVA缓存机制;了解工作流、ERP、EAI工作机制并有实际项目经验;老实说,一般面试官看到上面的简历就会想让这个人来面试了,因为真的你SSH,ORACLE,ERP或者是EAI等工作过5年很利害了已经,于

打造全国最全的AI Agent开发知识领域的博客 1万+

闲人闲谈PS之一项目库存跨公司业务STO解决方案--SAP闲人的开篇

写这篇文章之前,简单说一下发这篇文章的动机。也算是在SAP这一行干了快10多年,在对一个模块了解越来越深入,越发觉自己的SAP知识浅薄。总的来说,和多数顾问一样,对于**标准功能**的应用业务场景理解还是存在或多或少的知识盲区。 因为一个偶然,看到SAP团子君的文章,分享了很多干货文章。这也是自己一直想做的时候,不管水平高低与否,分享本身就意味着提升。好了废话不多说,先在优快云上发一篇吧,困惑自己将近10年的问题的解决方案。 业务场景:在项目型企业中,通常会有这样的业务,母公司和客...

SAP闲人的博客 9266

基于STM32设计的老人摔倒检测报警系统(OneNet+MQTT)(235)

基于STM32设计的老人摔倒检测报警系统,不仅能够实时监测老人的位置信息,方便在紧急情况下快速定位,还能通过陀螺仪模块精确检测老人的身体姿态,一旦判断为摔倒状态,系统将立即触发蜂鸣器报警,并通过4G网络向指定联系人发送短信警示,确保老人能够迅速得到援助。此外,系统还支持老人主动按下设备上的按键发送求助短信,增强了系统的灵活性和实用性。

4690
上一篇: think in java interview-高级开发人员面试宝典(七)
下一篇: think in java interview-高级开发人员面试宝典(九)
7star_java
博客等级 码龄15年 80粉丝 127原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值