【Java】Java学习笔记总结(二)

来源:互联网 发布:算法技术手册pdf 编辑:程序博客网 时间:2024/05/22 13:52

2013-07-22

1. AWTSwing的区别,如何设置look and feel?如何往JFrame添加组件。

答:AWT 是抽象窗口组件工具包,是 java 最早的用于编写图形节目应用程序的开发包。
Swing 是为了解决 AWT 存在的问题而新开发的包,它以 AWT 为基础的。

设置look and feel

try{
    UIManager.setLookAndFeel(外观名称);
   }catch(Exception e){}

方法setLookAndFeel的一些参数:

UIManager.getCrossPlatformLookAndFeelClassName()

--Java的界面外观所有平台均一致.

UIManager.getSystemLookAndFeelClassName()

--指定为当前平台的界面外观.32Windows平台Windows界面外观Mac OS平台Mac OS界面外观Sun平台CDE/Motif界面外观.

"javax.swing.plaf.metal.MetalLookAndFeel"

--指定为Java的界面外观也就是方法UIManager.getCrossPlatformLookAndFeelClassName()的返回值.

"com.sun.java.swing.plaf.windows.WindowsLookAndFeel"

--指定为Windows的界面外观仅在Windows平台起作用.

"com.sun.java.swing.plaf.motif.MotifLookAndFeel"

--指定为CDE/Motif的界面外观可以在所有平台起作用.

"javax.swing.plaf.mac.MacLookAndFeel"

--指定为Mac OS的界面外观仅在Mac OS平台起作用

 Swing 程序用JFrame 对象实现了它们的窗口。JFrame 类是AWT Frame 类的一个子类。它还加入了一些Swing 所独有的特性。与 Frame 的使用十分相似。唯一的区别在于,不能将组件加入到JFrame中。可以或者将组件加入到JFrame content pane(内容面板中,或者提供一个新的content pane(内容面板)

JFrame添加组件有两种方式:
  1)用 getContentPane ()方法获得JFrame的内容面板,再对其加入组件:frame. getContentPane ().add(childComponent)
  2)建立一个JpanelJDesktopPane之类的中间容器,把组件添加到容器中,用setContentPane()方法把该容器置为JFrame的内容面板:
    JPanel contentPane = new JPanel();
    ……//把其它组件添加到Jpanel;
    frame.setContentPane(contentPane);
    //contentPane对象设置成为frame的内容面板 

2. 说出常用的几个布局管理器和其特点。

答:常用的几个布局管理器和其特点:

------特点 
java.awt ---CardLayout--- 将组件象卡片一样放置在容器中,在某一时刻只有一个组件可见。 
java.awt--- FlowLayout--- 将组件按从左到右而后从上到下的顺序依次排列,一行不能放完则折到下一行继续放置。 
java.awt ---GridLayout ---形似一个无框线的表格,每个单元格中放一个组件。 
java.awt ---BorderLayout ---将组件按东、南、西、北、中五个区域放置,每个方向最多只能放置一个组件。 
java.awt--- GridBagLayout--- 非常灵活,可指定组件放置的具体位置及占用单元格数目。 

3. FrameDialog默认的布局管理器是什么,Panel的又是什么?

答:Frame默认的布局管理器是:BorderLayout

Dialog默认的布局管理器是:BorderLayout

Panel默认的布局管理器是:FlowLayout


2013-07-23

IO写入和复制文件

//package com.app;import java.io.*;public class Test_IODemo {public static void main(String[] args) {ForFileWriter("用FileWriter写入文件", "以FileWriter写入.txt");ForBufferedWriter("用BufferedWriter写入文件", "以BufferedWriter写入.txt");FileCopy1("我.txt", "字符流复制.txt");FileCopy2("我.txt", "字节流复制.txt");FileCopy3("我.txt", "处理流复制.txt");}//用FileWriter写入文件public  static void ForFileWriter(String string,String fileName) {File file = new File(fileName);try {FileWriter fWriter = new FileWriter(file);fWriter.write(string);fWriter.close();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}//用BufferedWriter写入文件public static void ForBufferedWriter(String string,String desFile) {BufferedWriter bWriter = null;try {bWriter = new BufferedWriter(new FileWriter(new File(desFile)));bWriter.write(string.toString());bWriter.close();} catch (Exception e) {e.printStackTrace();}}//字符流复制public static void FileCopy1(String readfile,String writeFile) {try {FileReader input = new FileReader(readfile);FileWriter output = new FileWriter(writeFile);int read = input.read();while ( read != -1 ) {output.write(read);read = input.read();}input.close();output.close();} catch (IOException e) {System.out.println(e);}}//字节流复制public static void FileCopy2(String readfile,String writeFile) {try {FileInputStream input = new FileInputStream(readfile);FileOutputStream output = new FileOutputStream(writeFile);int read = input.read();while ( read != -1 ) {output.write(read);read = input.read();}input.close();output.close();} catch (IOException e) {System.out.println(e);}}//处理流复制public static void FileCopy3(String readfile,String writeFile) {BufferedReader bReader = null;BufferedWriter bWriter = null;String line = null; try {bReader = new BufferedReader(new FileReader(new File(readfile)));bWriter = new BufferedWriter(new FileWriter(new File(writeFile)));while ((line = bReader.readLine())!=null) {bWriter.write(line);bWriter.newLine();}bWriter.close();bReader.close();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}

2013-07-24

1. 使用SwingIO设计一个记事本程序。

答:java文件见Test_Notepad.java

http://blog.csdn.net/jueblog/article/details/9457517

可执行文件见notepad.exe

2. 什么是对象序列化和反序列化?说一下具体实现的核心代码;Serializable接口有什么作用。

答:把Java对象转换为字节序列的过程称为对象的序列化。
  把字节序列恢复为Java对象的过程称为对象的反序列化。
  对象的序列化主要有两种用途:
  1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
  2) 在网络上传送对象的字节序列。

对象序列化:

  public static void ser(Person p, String fileName){  ObjectOutputStream oos = null;  try {  oos = new ObjectOutputStream(new FileOutputStream(new File(fileName)));  oos.writeObject(p);  } catch (Exception e) {  // TODO Auto-generated catch block  e.printStackTrace();  }  }

对象的反序列化:

public static void unSer(String fileName){try {ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(fileName)));Person p = (Person)ois.readObject();System.out.println(p.getAge() + p.getName());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}

3. 给定一个目录,输出其中的子目录或者文件名。

答:Java文件见 Text_IO_File.java

import java.io.*;//给定一个目录,输出其中的子目录或者文件名。//并按条件筛选输出含有指定字符串的文件public class Text_IO_File {public static void main(String[] args) {File directory = new File("");String pathString = null;try{    pathString = directory.getCanonicalPath();//获取标准的路径}catch(Exception e){}System.out.println("当前目录下的所有文件:");FileTest_List(pathString);System.out.println("当前目录下的所有Java文件:");FileTest_List_Choice(pathString, ".java");}//返回路径名下目录中的文件和目录。public static void FileTest_List(String fileName) {try {File f=new File(fileName);String[] arrStrings = f.list();for(String string : arrStrings){System.out.println(string);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}//返回路径名下目录中含choice的文件名public static void FileTest_List_Choice(String fileName,final String choice) {try {File f=new File(fileName);String[] arrStrings = f.list(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {// TODO Auto-generated method stubreturn name.indexOf(choice) != -1;}});for(String string : arrStrings){System.out.println(string);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}

4. 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。

答: Java文件见 Test_Merge.java

//package com.app;import java.io.*;public class Test_Merge {public static void main(String[] args) {WordMarge("Word1.txt", "Word2.txt", "WordMarge.txt");}//将readfile1文件中的单词与readfile2文件中的单词交替合并到writeFile文件中public static void WordMarge(String readfile1,String readfile2,String writeFile) {      BufferedReader bReader1 = null;      BufferedReader bReader2 = null;      BufferedWriter bWriter = null;      String line1 = null;       String line2 = null;       try {          bReader1 = new BufferedReader(new FileReader(new File(readfile1)));         bReader2 = new BufferedReader(new FileReader(new File(readfile2)));         bWriter = new BufferedWriter(new FileWriter(new File(writeFile)));          while ((line1 = bReader1.readLine())!=null | (line2 = bReader2.readLine())!=null) {        if(line1 != null) {              bWriter.write(line1);              bWriter.newLine();          }          if(line2 !=null) {              bWriter.write(line2);              bWriter.newLine();          }}        bWriter.close();          bReader1.close();          bReader2.close();      } catch (Exception e) {          // TODO: handle exception          e.printStackTrace();      }  }  }

2013-07-25

线程的同步

//1package com.app;/** * Java线程:线程的同步 */import java.util.concurrent.*;public class Test0725_Thread_Syn4 {public static void main(String[] args) {final ExecutorService exec = Executors.newFixedThreadPool(1);Callable<String> call = new Callable<String>() {public String call() throws Exception {// 开始执行耗时操作int cash = 300;String name = "张三";System.out.println(name + "现在有" + cash + "元存款");User u = new User(name, cash);String[] arr = { "线程A", "线程B", "线程C", "线程D", "线程E", "线程F","线程G", "线程H", "线程I", "线程J" };for (int i = 0; i < 10; i++) {MyThread th = new MyThread(arr[i], u,(int) (Math.random() * 1000 - 500));th.start();}Thread.sleep(1000 * 5);return "线程执行完成.";}};try {Future<String> future = exec.submit(call);String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为1 秒System.out.println("任务成功返回:" + obj);} catch (TimeoutException ex) {System.out.println("\n处理超时啦....");System.exit(0);} catch (Exception e) {System.out.println("处理失败.");e.printStackTrace();}   try {    Future<String> future = exec.submit(call);    String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); //任务处理超时时间设为 1 秒    System.out.println("任务成功返回:" + obj);            } catch (TimeoutException ex) {    System.out.println("处理超时啦....");    ex.printStackTrace();            } catch (Exception e) {    System.out.println("处理失败.");    e.printStackTrace();            } exec.shutdown();     // 关闭线程池  /*int cash2 = 100;String name2 = "李四";System.out.println(name2 + "现在有" + cash2 + "元存款");User u2 = new User(name, cash);String[] arr2 = {"线程A","线程B","线程C","线程D","线程E","线程F"};for (int i = 0; i < 6; i++) {MyThread th2 = new MyThread(name2+arr2[i], u2, (int)(Math.random()*1000-500));th2.start();}*/}}class MyThread extends Thread {private User u;private int x = 0;MyThread(String name, User u, int x) {super(name);this.u = u;this.x = x;}public void run() {u.oper(x);}}class User {private String code;private int cash;private int time = 0;User(String code, int cash) {this.code = code;this.cash = cash;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public int getCash() {return cash;}public void setCode(int cash) {this.cash = cash;}/** * 业务方法 *            添加x万元 */public synchronized void oper(int x) {if ((this.cash +x >= 1000) && x > 0 ) {System.out.println(Thread.currentThread().getName() + "暂停!"+"当前账户余额为:" + this.cash + ",您还想存" +x + ",太多了!");try {Thread.yield();//Thread.sleep(100);this.wait();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}else if (this.cash + x <0) {System.out.println(Thread.currentThread().getName() + "暂停!"+"当前账户余额为:" + this.cash + ",小于所取额 " +x +",余额不足!");try {Thread.yield();//Thread.sleep(100);this.wait();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}} if(this.cash < 1000 && this.cash > 0 && (this.cash + x >= 0) && (this.cash + x <= 1000)){this.cash += x;System.out.println(Thread.currentThread().getName() + "运行结束,增加“ "+ x + " ”,当前用户账户余额为:" + this.cash);time++;this.notifyAll();}this.notifyAll();}@Overridepublic String toString() {return "User{" + "code='" + code + '\'' + ", cash=" + cash + '}';}}

2013-07-26

1. 同步有几种实现方法。

答:Java的同步可以用synchronized关键字来实现。
主要有两种方法:
sychronized同步代码,需要绑定一个对象,如synchronized(obj){}
sychronized同步一个方法,是对方法进行线程同步。如public void synchronized methodA(){}

2. 线程的基本状态(生命周期)

答:java中,每个线程都需经历创建、就绪、运行、阻塞和终止五种状态,线程从创建到终止的状态变化称为生命周期。

new运算符和Thread类或其子类建立一个线程对象后,该线程就处于创建状态。

创建--->就绪:通过调用start()方法

就绪--->运行:处于就绪状态的线程一旦得到CPU,就进入运行状态并自动调用自己的run()方法

运行--->阻塞:处于运行状态的线程,执行sleep()方法,或等待I/O设备资源,让出CPU并暂时中止自己运行,进入阻塞状态

阻塞--->就绪:睡眠时间已到,或等待的I/O设备空闲下来,线程便进入就绪状态,重新到就绪队列中等待CPU。当再次获得CPU时,便从原来中止位置开始继续运行。

运行--->终止:(1)(正常情况下)线程任务完成
                 (2)(非正常状况)线程被强制性的中止,如通过执行stop()destroy()方法来终止一个线程

3. 简述synchronized和java.util.concurrent.locks.Lock的异同。

答:主要相同点:

  Lock能完成synchronized所实现的所有功能。

主要不同点:

1)Lock有比synchronized更精确的线程语义和更好的性能。

2)synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。

4. 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

答:Java代码见ThreadTest.java

//package com.app;public class ThreadTest {static int t = 10;static final int TIME = 5;public static void main(String[] args) {ThreadTest test = new ThreadTest();AddTest thread1 = test.new AddTest();MinusTest thread2 = test.new MinusTest();for (int i = 0; i < 2; i++) {new Thread(thread1).start();new Thread(thread2).start();}}private synchronized void Add() {t++;System.out.println(Thread.currentThread().getName() + "--加法--" +t);}class AddTest implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < TIME; i++) {Add();}}}private synchronized void Minus() {t--;System.out.println(Thread.currentThread().getName() + "--减法--" +t);}class MinusTest implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < TIME; i++) {Minus();}}}}