java基础知识学习整理

本文深入浅出地介绍了Java中的重要概念,包括运算符、构造方法、重载、多态、抽象类、接口、集合类、文件操作及流处理等内容。通过实例演示了各种特性的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:Java对 加 运 算 符 进 行 了 扩 展 ,使 它 能 够 进 行 字 符 串 的连 接,如"abc"+"de",得到 串 "abcde"。

与 C、 C++不 同 ,对 取 模 运 算 符 %来 说 ,其 操 作 数 可 以为浮点 数, 如37.2%10=7.2。

2:

Java中 ,任 何 数 据 类 型 的 数 据 (包 括 基 本 类 型 和 组 合 类 型)都可 以 通 过 ==或!=来 比 较 是 否 相 等 (这 与 C、 C++不 同 )。

关 系 运 算 的 结 果 返 回 true或 false,而不是C、C++中 的 1或 0。

关 系 运 算 符 常 与 布 尔 逻 辑 运 算 符 一 起 使 用 ,作 为 流 控 制语句 的 判 断 条件 。 如

if( a>b && b==c)

3:如何区分&&和&呢?它们之间区别在于,如果左边的操作数是false,则&&条件表达式将不对运算符右边的操作数进行判断,因为在这种情况下,结果肯定是false.从此可以看出,左边操作数是false时,运算速度会快一些。&运算符左边的操作数是false,并且结果已经肯定不成立,右边的操作数(f3*number-27 )>100)还要计算。所以,我们可以使用&&加快程序的运行速度,忘记&吧,对吗?不对。这将取决于你要操作的内容。在绝大多数情况下,你可以使用&&,但有时你需要计算右边的操作数,同样也有一些例子,在左边操作数是false的情况下,不希望计算右边的操作数。

4:构造方法与类名相同并且没有返回值,不写void。使用构造方法来初始化变量,在new的时候调用类的构造方法,同时初始化变量
 public class Person{
  int id;
  int age = 20;
  Person(int _id, int _age){ //注意不能写void,否则编译会当作普通方法而不是构造方法
  id = _id;
  age = _age;
  }
  public static void main(String[] args){
  Person person = new Person(1,25);//调用构造方法
  }
 }
 5: 类名首字母应该大写,方法名和变量名小写。

6:方法的重载是指一个类中可以定义有相同名字,但参数不同的多个方法。调用时,会根据不同的参数列表选择对应的方法
 public class Test{
  void max(int a, int b){
  System.out.println(a>b? a:b);
  }
  void max(float a, float b){
  System.out.println(a>b? a:b);
  }
 }

7:多态:要有继承,要有重写,父类引用指向子类对象
 class Animal{
  private String name;
 
  Animal(String name){
  this.name = name;
  }
 
  public void enjoy(){
  System.out.println("叫声....");
  }
 }
 
 public Cat extends Animal{
  private String eyesColor;
 
  Cat(String n, String c){
  super(n);
  eyesColor = c;
  }
 
  public void enjoy(){
  System.out.println("猫叫声....");
  }
 }
 public Dog extends Animal{
  private String furColor;
 
  Dog(String n, String c){
  super(n);
  furColor = c;
  }
 
  public void enjoy(){
  System.out.println("狗叫声....");
  }
 }
 
 class Lady{
  private String name;
  private Animal pet;
 
  Lady(String name,Animal pet){
  this.name = name;
  this.pet = pet;
  }
  public void myPetEnjoy(){
  pet.enjoy();
  }
 }
 
 public class Test{
public static void main(String[] args){
  Cat c = new Cat("catname","blue");
  Dog d = new Dog("dogname","yellow");
  Lady l1 = new Lady("l1",c);
  Lady l2 = new Lady("l2",d);
  l1.myPetEnjoy();
  l2.myPetEnjoy();
  }
 }
 8: 父类的抽象方法就是用来给子类重写的,然后给每个类去实现。一个类如果有抽象类,则这个类必须被声明为抽象类abstract
 抽象类无法对其实例化,抽象方法只需要声明不需要实现。
 
 final的变量的值不能够被改变,final的方法不能被重写,final的类不能被继承

9:接口:                                                                                        
接口(interface)是抽象方法和常量值的定义的集合                                               
从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的实现
public interface Runner{                                                                      
public static final int id = 1;//属性默认为public static final                             
public void start();//方法默认为抽象的abstract,也只能是public                              
public void run();                                                                         
public void stop();                                                                        
}                                                                                             
                                                                                              
接口还可以继承其他的接口,并添加新属性和方法                                                  
例子:                                                                                        
interface Singer{                                                                             
public void sing();                                                                        
public void sleep();                                                                       
}                                                                                             
interface Painter{                                                                            
public void painter();                                                                     
}                                                                                             
class Student implements Singer,Painter{                                                      
private String name;                                                                     
Student(String name){                                                                    
this.name = name;                                                                    
}                                                                                        
public void study(){                                                                     
System.out,println("studing");                                                       
}                                                                                        
public void sing(){                                                                      
System.out,println("sing");                                                          
}                                                                                        
public void sleep(){                                                                     
System.out,println("sleep");                                                         
}                                                                                        
public void painter(){                                                                   
}                                                                                        
}                                                                                             
//接口和实现类之间存在多态性                                                                  
public class Test{                                                                            
public static void main(String[] args){                                                    
Singer s1 = new Student("le");                                                       
s1.sing();//只能看到Singer自己的方法,看不到student自己的方法                        
s1.sleep();                                                                          
                                                                                    
}                                                                                          
}                                                                                             

10:

 Map是java中的接口,Map.Entry是Map的一个内部接口。

         Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。

         Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。

         

        由以上可以得出,遍历Map的常用方法:

       1.  Map map = new HashMap();

           Irerator iterator = map.entrySet().iterator();

           while(iterator.hasNext()) {

                   Map.Entry entry = iterator.next();

                   Object key = entry.getKey();

                   //

           }

       2.Map map = new HashMap(); 

           Set  keySet= map.keySet();

           Irerator iterator = keySet.iterator;

           while(iterator.hasNext()) {

                   Object key = iterator.next();

                   Object value = map.get(key);

                   //

           }

 

       另外,还有一种遍历方法是,单纯的遍历value值,Map有一个values方法,返回的是value的Collection集合。通过遍历collection也可以遍历value,如

      Map map = new HashMap();

      Collection c = map.values();

      Iterator iterator = c.iterator();

      while(iterator.hasNext()) {

             Object value = iterator.next(); 

     }

11:

Java中的Set集合类

1. 概述   

        Java 中的Set和正好和数学上直观的集(set)的概念是相同的。Set最大的特性就是不允许在其中存放的元素是重复的。根据这个特点,我们就可以使用Set 这个接口来实现前面提到的关于商品种类的存储需求。Set 可以被用来过滤在其他集合中存放的元素,从而得到一个没有包含重复新的集合。

 

2. 常用方法

        按照定义,Set 接口继承 Collection 接口,而且它不允许集合中存在重复项。所有原始方法都是现成的,没有引入新方法。具体的 Set 实现类依赖添加的对象的 equals() 方法来检查等同性。

        各个方法的作用描述:

        public int size() :返回set中元素的数目,如果set包含的元素数大于Integer.MAX_VALUE,返回Integer.MAX_VALUE;

        public boolean isEmpty() :如果set中不含元素,返回true ;
        public boolean contains(Object o) :如果set包含指定元素,返回true ;
        public Iterator iterator() : 返回set中元素的迭代器,元素返回没有特定的顺序,除非set提高该保证的某些类的实例 ;
        public boolean add(Object o) :如果set中不存在指定元素,则向set加入 ;
        public boolean remove(Object o) :如果set中存在指定元素,则从set中删除 ;
        public boolean removeAll(Collection c) :如果set包含指定集合,则从set中删除指定集合的所有元素 ;
        public void clear() :从set中删除所有元素;

 

3. 原理分析

        HashSet的元素存放顺序和添加进去时候的顺序没有任何关系;而LinkedHashSet 则保持元素的添加顺序;TreeSet则是对我们的Set中的元素进行排序存放。 
        一般来说,当要从集合中以有序的方式抽取元素时,TreeSet 实现就会有用处。为了能顺利进行,添加到 TreeSet 的元素必须是可排序的。 而同样需要对添加到TreeSet中的类对象实现 Comparable 接口的支持。对于Comparable接口的实现。假定一棵树知道如何保持 java.lang 包装程序器类元素的有序状态。一般说来,先把元素添加到 HashSet,再把集合转换为 TreeSet 来进行有序遍历会更快。这点和HashMap的使用非常的类似。 
        其实Set的实现原理是基于Map上面的。Set中很多实现类和Map中的一些实现类的使用上非常的相似。Map中的“键值对”,其中的 “键”是不能重复的。这个和Set中的元素不能重复一致,其实Set利用的就是Map中“键”不能重复的特性来实现的。 HashSet的巧妙实现:就是建立一个“键值对”,“键”就是我们要存入的对象,“值”则是一个常量。这样可以确保, 我们所需要的存储的信息之是“键”。而“键”在Map中是不能重复的,这就保证了我们存入Set中的所有的元素都不重复。而判断是否添加元素成功,则是通 过判断我们向Map中存入的“键值对”是否已经存在,如果存在的话,那么返回值肯定是常量:PRESENT ,表示添加失败。如果不存在,返回值就为null 表示添加成功。

12:流操作:

输入输出流都是站在程序的角度上来看的,而不是从文件的角度上。

1、描述:流是字节数据或字符数据序列。Java采用输入流对象和输出流对象来支持程序对数据的输入和输出。输入流对象提供了数据从源点流向程序的管道,程序可以从输入流对象读取数据;输出流对象提供了数据从程序流向终点的管道,程序通过该管道把数据写到终点。所有的关于输入/输出的类都包含在java.io的包中。
2、File类:它主要关心的是文件的具体属性,而非内容,定义了许多方法,实现对文件的创建、删除等操作。
code:
import java.io.*;
public class Test
{
 public static void main(String args[])throws Exception
 {
  File file1=new File("w1.txt");//在当前目录下
  file1.createNewFile();//得到文件w1.txt
  file1.mkdir();//得到目录w1.txt
  File file2=new File("D:\\javaprogram\\text\\w2.txt");//指定目录
  file2.createNewFile();//得到文件w2.txt
  //用静态字段separator获得系统分隔符,保证程序通用性
  File fDir=new File(File.separator);//作为字符是'\',作为File对象为当前根目录
  String fStr="javaprogram"+File.separator+"text"+File.separator+"w3.txt";
  File file3=new File(fDir,fStr);
  file3.createNewFile();//得到文件w3.txt
  file1.delete();
  file2.delete();
  file3.delete();
  //delete()方法删除文件,调用即删除,而deleteOnExit()是在JVM终止时才删除
  //这样就得以建立临时文件以存储临时数据,临时文件保存在临时文件夹
  //要找临时文件夹,请查看环境变量temp的设置
  for(int i=0;i<5;i++)
  {
   File file=File.createTempFile("wang",".temp");
   file.deleteOnExit();
  }
  Thread.sleep(3000);
  //下面的一段程序将实现,打印指定目录下的.java文件的信息
  File f=new File("d:\\javaprogram");
  if(f.exists())//判断文件是否存在
  {
   if(f.isDirectory())//判断文件是目录还是标准文件
   {
    //调用带参数的listFiles()方法返回满足特定过虑器的
    //此抽象路径名所表示目录中的文件和目录的抽象路径名数组
    File[] fname=f.listFiles(new FilenameFilter()
    {
     //匿名类实现接口FilenameFileter的唯一方法
     public boolean accept(File dir, String name) 
     {
      return name.indexOf(".java")!=-1;
     }
    });
    for(int i=0;i<fname.length;i++)
    {
     System.out.println(fname[i]);
    }
   }
  }
  else
  {
   System.out.println("文件夹不存在.");
  }
 }
}

3、字节流:
程序运行中常的I/O操作包括向标准设备输入输出数据和文件输入输出。对于前者,java定义了三个直接使用的流对象:System.err(标准错误输出)、System.out(标准输出)和System.in(标准输入);对于后者,可以使用FileOutputStream和FileInputStream。
code:
import java.io.*;
public class Test
{
 static final String file1="D:\\javaprogram\\w1.txt";
 static final String file2="E:\\database\\w2.txt";
 static final String file3="E:\\wmpub\\w3.txt";
 public static void main(String args[])throws IOException
 {
  /*//关于System.in
  int data;
  while ((data=System.in.read())!=-1)//Ctrl+c结束输入
  {
   System.out.write(data);
  }*/
  //下面的程序段用以向file1文件写入,把其内容的一部分复制到file2
  //再把file2文件完整地复制到file3,并打印出来
  FileOutputStream fos1=new FileOutputStream(file1);
  FileOutputStream fos2=new FileOutputStream(file2);
  FileOutputStream fos3=new FileOutputStream(file3);
  fos1.write("今天是2008年8月3号,离北京奥运会还有5天,心里非常激动啊.".getBytes());
  fos1.close();
  FileInputStream fis1=new FileInputStream(file1);
  fis1.skip(19);//跳过19个字节
  byte[] buf=new byte[fis1.available()];
  fis1.read(buf);
  fis1.close();
  System.out.println(new String(buf));
  fos2.write(buf);
  fos2.close();
  FileInputStream fis2=new FileInputStream(file2);
  while(fis2.available()>0)
  {
   byte[] b=new byte[fis2.available()];
   int let=fis2.read(b);
   if(let==-1)break;
   fos3.write(b,0,let);
  }
  System.out.println("复制成功!");
  fis2.close();
  fos3.close();
  //以下程序段实现了一个图像文件的复制
  FileInputStream a=new FileInputStream("4.jpg");
  FileOutputStream b=new FileOutputStream("3.jpg");
  byte c[]=new byte[a.available()];
  a.read(c);
  b.write(c);
  a.close();
  b.close();
 }
}

4、字符流(FileWriter and FileReader)

import java.io.*;
public class Test
{
 public static void main(String args[])
 {
  //本程序完成从控制台读入文件名,并实现复制
  int length;
  char buf[]=new char[100];
  try
  {
   FileReader in=new FileReader(args[0]);
   FileWriter out=new FileWriter(args[1]);
   length=in.read(buf);
   while(length!=-1)
   {
    out.write(buf,0,length);
    //字符流读取通过read()的返回值判断是否读到文件末尾
    //我刚才忘记加这条语句,文件被一直写,都死机了,重启后一看,写了2.6G
    length=in.read(buf);
   }
   in.close();
   out.close();
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
 }

5、过滤流之一
    Java利用过滤流可以在读写数据的同时对数据进行处理,以达到性能的改善,提高程序执行效率。将过滤流和某个输入流或输出流(节点流)连接。连接是通过在过滤流的构造方法中指定入口参数——节点流来实现的。
  §BufferedInputStream:
                        FileInputStream fis=new FileInputStream("w1.txt");
                        BufferedInputStream bis=new BufferedInputStream(fis);
                        byte[] buf=new byte[100];
                        int len=bis.read(buf,0,len);
                        System.out.println(new String(buf,0,len));
                        bis.close();
        §BufferedOutputStream:
                        FileOutStream fos=new FileOutputStream("w2.txt");
                        BufferedOutputStream bos=new BufferedOutputStream(bos);
                        bos.write("好好学习,天天向上".getBytes());
                        bos.flush();
                        bos.close();
    也可以是匿名创建:如:BufferedOutputStream bos=new BufferedOutputStream(new FileInputStream("w2.txt")); 
     BufferedReader和BufferedWirter与此类似,不过是分别指定WriterReader类型的参数罢了。
一个实例程序:
import java.io.*;
public class Test
{
 public static void main(String[] args)
 {
  try
  {
   FileInputStream in=new FileInputStream(args[0]);
   BufferedInputStream bufIn=new BufferedInputStream(in);
   int limit;
   bufIn.mark(limit=bufIn.available());//在当前位置打上标记
   for(int i=0;i<limit;i++)
    System.out.print((char)(bufIn.read()));
   System.out.println();
   bufIn.reset();//reset缓冲区标志
   int c;
   while((c=bufIn.read())>=0)System.out.print((char)c);
   bufIn.close();
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
 }
}

5、过滤流之二基本类型数据传输:DataInputStream和DataOutputStream
import java.io.*;
public class Test
{
 public static void main(String args[])
 {
  try
  {
   DataOutputStream dos=new DataOutputStream(
    new BufferedOutputStream(new FileOutputStream(
     "d://javaprogram//w.txt")));
   dos.writeInt(5);
   dos.writeUTF("你好");
   dos.writeBoolean(true);
   dos.writeDouble(3.1415926);
   dos.writeBytes("ok!");
   dos.writeChars("bye bye");
   dos.close();
   DataInputStream dis=new DataInputStream(
    new BufferedInputStream(new FileInputStream(
        "d://javaprogram//w.txt")));
   //读出的顺序应与写入的顺序一致
   System.out.println(dis.readInt());
   System.out.println(dis.readUTF());
   System.out.println(dis.readBoolean());
   System.out.println(dis.readDouble());
   byte b[]=new byte[3];
   dis.readFully(b);
   for(int j=0;j<3;j++)System.out.print((char)b[j]);
   System.out.println();
   StringBuffer st3=new StringBuffer();
   for(int j=0;j<7;j++)st3.append(dis.readChar());
   System.out.println(st3.toString());
   dis.close();
  }
  catch (IOException e)
  {
   System.err.println(e.toString());
  }
 }
}
6、过滤流之三:I/O流的链接图:
   
7、字节和Unicode字符的桥梁:InputStreamReader、OutputStreamWriter
code:
import java.io.*;
public class Test
{
 public static void main(String[] args)throws IOException
 {
  //文件读写
  FileOutputStream fos=new FileOutputStream("w.txt");
  OutputStreamWriter osw=new OutputStreamWriter(fos);
  BufferedWriter bw=new BufferedWriter(osw);
  bw.write("今天是2008年8月3日,离北京奥运还有5天!");
  bw.close();
  FileInputStream fis=new FileInputStream("w.txt");
  InputStreamReader isr=new InputStreamReader(fis);
  BufferedReader br=new BufferedReader(isr);
  System.out.println(br.readLine());
  br.close();
  //控制台读写
  BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
  BufferedWriter bw1=new BufferedWriter(new OutputStreamWriter(System.out));
  String strLine,str="";
  while((strLine=br1.readLine())!=null)//Ctrl+c结束输入
  {
   str+=strLine;
   System.out.println(strLine);
  }
  br1.close();
  bw1.write(str,0,str.length());
  bw1.write((int)('\n')); //将回车符输入bw1
  bw1.flush();
  bw1.close();
 }
}
8、管道流:PipedInputStream、PipedOutputStream
      作用:用于线程间的通信,一个线程的pipedInputStream对象从另一个线程的PipedOutputStream对象读取输入,要使管道流有用,必须同时构造管道输入流和管道输出流。
例子(孙鑫老师的例子):
import java.io.*;
class Producer extends Thread
{
 private PipedOutputStream pos;
 public Producer(PipedOutputStream pos)
 {
  this.pos=pos;
 }
 public void run()
 {
  try
  {
   pos.write("Hello,welcome you!".getBytes());
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}
class Consumer extends Thread
{
 private PipedInputStream pis;
 public Consumer(PipedInputStream pis)
 {
  this.pis=pis;
 }
 public void run()
 {
  try
  {
   byte[] buf=new byte[100];
   int len=pis.read(buf);
   System.out.println(new String(buf,0,len));
   pis.close();
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}
public class Test
{
 public static void main(String args[])
 {
  PipedOutputStream pos=new PipedOutputStream();
  PipedInputStream pis=new PipedInputStream();
  try
  {
   pos.connect(pis);
   new Producer(pos).start();
   new Consumer(pis).start();
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}
9、PrintWriter类:创建的输出流可以使用print和println方法,按Unicode字符形式输出,输出的数据可读性较好。
        §打印流建立文本文件:
                                PrintWriter out=new PrintWriter(new FileWriter(1.dat));
                                String str="天呢,我告诉你吧:";
                                char[] z={'北','京','奥','运','会','在'};double g=2008;
                                out.println(st);out.print(z);out.print(g);out.println("年08月08日08时08分08秒");
                                out.close();
        §打印流在屏幕上显示文本
                                PrintWriter out=new PrintWriter(System.out);
                                其余同上,此处略
10、文件的随机读写:RandomAccessFile
import java.io.*;
public class Test
{
 public static void main(String args[])throws Exception
 {
  int lineNo;//读到的行号
  long fp;//文件指针
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  RandomAccessFile raf=new RandomAccessFile("w.txt","rw");
  System.out.println("请输入6个字符串");
  int[] len=new int[12];
  String[] str=new String[12];
  for(int i=0;i<6;i++)
  {
   System.out.println("行号"+(i+1)+":");
   str[i]=br.readLine();
   len[i]=str[i].length();
   raf.write((str[i]+"\n").getBytes());
  }
  while(true)
  {
   fp=0;
   raf.seek(0);
   System.out.println("你要显示第几行?"+"(1--6)");
   lineNo=Integer.parseInt(br.readLine());
   for(int i=1;i<lineNo;i++)
    fp=fp+(long)len[i-1]+1;
   raf.seek(fp);
   System.out.println("第"+lineNo+"行"+":"+raf.readLine());
   System.out.println("继续吗?"+"(y/n)");
   if((br.readLine().equals("n")))break;
  }
  raf.seek(raf.length());
  System.out.println("继续写入6行数据:");
  for(int i=6;i<12;i++)
  {
   System.out.println("行号"+(i+1)+":");
   str[i]=br.readLine();
   len[i]=str[i].length();
   raf.write((str[i]+"\n").getBytes());
  }
  System.out.println("打印12行数据:");
  raf.seek(0);
  for(long i=0;i<raf.length();i=raf.getFilePointer())
  {
   System.out.println(raf.readLine());
  }
  raf.close();
 }
}
11、文件的压缩处理
 实例:
import java.io.*;
import java.util.*;
//ZipInputStream和ZipOutputStream在包java.util.zip中
import java.util.zip.*;
public class Test
{
 public static void main(String args[])throws Exception
 {
  //输入若干文件名,将所有文件压缩为w.zip
  ZipOutputStream zos=new ZipOutputStream(
   new BufferedOutputStream(new FileOutputStream("w.zip")));
  for(int i=0;i<args.length;i++)
  {
   BufferedInputStream bis=new BufferedInputStream(
    new FileInputStream(args[i]));
   //将每个要压缩的文件称为一个压缩入口,使用ZipEntry生成压缩入口对象
   //使用putNextEntry(ZipEntry entry)将压缩入口加入到压缩文件
   zos.putNextEntry(new ZipEntry(args[i]));
   int b;
   while((b=bis.read())!=-1)
    zos.write(b);
   bis.close();
  }
  zos.close();
  //解压缩文件并显示
  ZipInputStream zis=new ZipInputStream(
   new BufferedInputStream(new FileInputStream("w.zip")));
  ZipEntry z;
  while((z=zis.getNextEntry())!=null)//获得入口
  {
   System.out.println(z.getName());//显示文件初始名
   int x;
   while((x=zis.read())!=-1)
    System.out.write(x);
   System.out.println();
  }
  zis.close();
 }
}
12、编码与解码
 import java.util.*;
import java.nio.charset.*;
public class Test
{
 public static void main(String args[])throws Exception
 {
  //以下程序段打印当前计算机所能处理的标准 charset
  //Charset类位于java.nio.charset包中,此类定义了用于创建解码器和编码器
  //以及检索与 charset 关联的各种名称的方法。此类的实例是不可变的。
  //Charset.availableCharsets()返回一个映射
  //Map是java.util包中的一个接口
  Map m=Charset.availableCharsets();
  //keySet()方法返回此映射中包含的键的 set 视图
  Set names=m.keySet();
  //构造迭代器访问诸元素
  Iterator it=names.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
  //Properties 类位于java.util包中,表示了一个持久的属性集
  //System.getProperties()确定当前的系统属性。
  Properties pps=System.getProperties();
  pps.list(System.out);//打印属性
  //将系统文件的标准字符集改为:ISO-8859-1
  //设置的字符集,只是当前JVM上的字符集
  pps.put("file.encoding","ISO-8859-1");
  int data;
  byte[] buf=new byte[100];
  int i=0;
  while((data=System.in.read())!='q')
  {
   buf[i]=(byte)data;
   i++;
  }
  String str=new String(buf,0,1);
  System.out.println(str);
  //ISO-8859-1字符解码为Unicode字符(java使用)
  //Unicode字符编码为GBK字符
  //但并不是所有字符都能反编码回来,比如汉字将丢失高字节
  String strGBK=new String(str.getBytes("ISO-8859-1"),"GBK");
  System.out.println(strGBK);
 }

13、对象序列化
               对象的寿命常随着对象的程序的终止而终止,倘若需要对对象的状态进行保存,需要时再恢复。我们把对象的这种能够记录自己状态以便将来再生的能力,叫做对象的持续性(persistence)。对象通过写出描述自己状态的值——对象转化为字节流,来记录自己的这个过程叫对象的序列化(serialization)。  一个对象要能够实现序列化,必须实现Serializable接口,或者Externalizable接口。 
               一个对象被序列化时,只保存对象的非静态成员变量,如果一个对象的成员变量是一个对象,那么这个对象的数据成员也会被保存。如果一个可序列化的对象包含对某个不可序列化的对象的引用,那么整个序列化操作将会失败,并且会抛出一个NotSerializableException。但如果把这个引用标记为transient,那么对象仍然可以序列化。
                另外,对象序列化建立了一张对象网,将当前要序列化的对象中所持有的引用指向的对象都包含起来一起写入到文件,如果一次序列化几个对象,它们中的相同内容会被共享。
code:

import java.io.*;

public class Test
{
 public static void main(String[] args) throws Exception
 {
  Employee e1=new Employee("zhangsan",25,3000.50);
  Employee e2=new Employee("lisi",24,3200.40);
  Employee e3=new Employee("wangwu",27,3800.55);
  ObjectOutputStream oos=new ObjectOutputStream(
   new FileOutputStream("w.dat"));
  oos.writeObject(e1);
  oos.writeObject(e2);
  oos.writeObject(e3);
  oos.close();

  ObjectInputStream ois=new ObjectInputStream(
   new FileInputStream("w.dat"));
  Employee e;
  String strSal;
  for(int i=0;i<3;i++)
  {
   e=(Employee)ois.readObject();
   //设置自已需要的输出方式
   //strSal=(e.salary==0)?"不告诉你":String.valueOf(e.salary);
   //System.out.println(e.name+":"+e.age+":"+strSal);
   System.out.println(e.name+":"+e.age+":"+e.salary);
  }
  ois.close();
 }
}
class Employee implements Serializable
{
 String name;
 int age;
 transient double salary;
 transient Thread t=new Thread();
 public Employee(String name,int age, double salary)
 {
  this.name=name;
  this.age=age;
  this.salary=salary;
 }
 //重写方法,完成需要的操作,如果不重写,要想不写入某些数据可以标记为transient
 //本程序的数据salary就被标记为transient,打印时输出为0.0,如果是String将为null
 /*private void writeObject(java.io.ObjectOutputStream oos)throws IOException
 {
  oos.writeUTF(name);
  oos.writeInt(age);
  //System.out.println("Write Object");
 }
 private void readObject(java.io.ObjectInputStream ois)throws IOException
 {
  name=ois.readUTF();
  age=ois.readInt();
  //System.out.println("Read Object");
 }*/
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值