FileInputStream(文件输入、输出流) 示例


import java.io.*;
class FileInputStreamDemo{
public static void main(String[] args) throws Exception{
   int intSize;
   InputStream f = new FileInputStream("FileInputStreamDemo.java");
   System.out.println("Total Available Bytes: " + (intSize = f.available()));

   int n = intSize / 40 ;
   System.out.println("First " + n + " bytes of the file one read() at a time.");
   for(int i=0;i<n;i++){
    System.out.print((char)f.read());
   }
   System.out.println("\nStill Available :" + f.available());
   System.out.println("Reading the next " + n + " with one read(b[]) ");

   byte b[] = new byte[n];
   if(f.read(b) !=n){
    System.out.println("couldn't read " + n +"bytes.");
   }
   System.out.println(new String(b,0,n));
   System.out.println("\nStill Available :" + (intSize = f.available()));
   System.out.println("Skipping half of remaining bytes with skip()");
   f.skip(intSize/2);
   System.out.println("Still Available :" + f.available());
   System.out.println("Reading " + n/2 + " into the end of array.");
   if(f.read(b,n/2,n/2) !=n/2){
    System.out.println("couldn't read " + n/2 + "bytes.");
   }
   System.out.println(new String(b,0,b.length));
   System.out.println("\nStill Available :" + f.available());
   f.close();
}
}

 
 
 
FileOutputStream(文件输出流) 示例
 
import java.io.*;
class FileOutputStreamDemo{
public static void main(String[] args) throws Exception{
   String source = "Now is the time for all good men\n"
         +" to come to the aid of their country\n"
         +" and pat their due taxes.";
   byte buf[] = source.getBytes();
   //新建一文件输出流f0,用于将数据写入指定文件
   OutputStream f0 = new FileOutputStream("file1.txt");
   for(int i=0;i<buf.length;i+=2){
    f0.write(buf[i]);
   }
   f0.close();
   //新建一文件输出流f1,用于将数据写入指定文件

   OutputStream f1 = new FileOutputStream("file2.txt");
   f1.write(buf);
   f1.close();

   //新建一文件输出流f2,用于将数据写入指定文件

   OutputStream f2 = new FileOutputStream("file3.txt");
   f2.write(buf,buf.length-buf.length/4,buf.length/4);
   f2.close();
}
}

 
 
ByteArrayInputStream (字节数组输入流) 示例
 

import java.io.*;
class ByteArrayInputStreamDemo{
public static void main(String[] args) 
{
   String strTmp = "zhengzhi";
   byte b[] = strTmp.getBytes();

   //新建一字节数组输入流in,其缓冲区存放字节数组b的数据
   ByteArrayInputStream in = new ByteArrayInputStream(b);

   for(int i=0;i<2;i++){
    int c;

    //逐字节读取输入流in缓冲区中数据
    while((c=in.read())!=-1){
     if(i==0){

      //字节转换为char类型并从控制台输出
      System.out.print((char)c); 
     }else{

      //输出对应大写字母
      System.out.print(Character.toUpperCase((char)c));
     }
    }
    System.out.println();

    //重置in缓冲区位置
    in.reset();
   }
}
}

 
 
 
ByteArrayOutputStream(字节数组输出流) 示例
 
import java.io.*;
class ByteArrayOutputStreamDemo{
public static void main(String[] args) throws IOException{
   //新建一个ByteArray输出流对象f(内存中建立其缓冲区存放Byte数组)
   ByteArrayOutputStream f = new ByteArrayOutputStream();
   String s = "This should end up in the array";
   byte buf[] = s.getBytes();
   //将buf写入输出流f缓冲区中的Byte数组中

   f.write(buf);
   System.out.println("Buffer as a string");
   System.out.println(f.toString());
   System.out.println("Into array");

   //从输出流f缓冲区取出Byte[]的值赋给b
   byte b[] = f.toByteArray();
   for(int i=0;i<b.length;i++){
    System.out.print((char)b[i]);
   }
   System.out.println("\nTo an OutputStream()");

   //新建File输出流f2
   OutputStream f2 = new FileOutputStream("text.txt");

   //将ByteArray输出流f全部内容写入f2中
   f.writeTo(f2);
   f2.close();
   System.out.println("Doing a reset");

   //清空f缓冲区中的数据
   f.reset();
   for(int i=0;i<3;i++){
    f.write('X');
   }
   System.out.println(f.toString());
}
}

 

 

BufferedInputStream(缓冲输入流) 示例

import java.io.*;
class BufferedInputStreamDemo{
public static void main(String[] args) throws IOException{
   String s = "This is a &copy; copyright symbol but this is &copy not.\n";
   byte buf[] = s.getBytes();
   ByteArrayInputStream in = new ByteArrayInputStream(buf);
   BufferedInputStream f = new BufferedInputStream(in);
   int c;
   boolean marked = false;
   while((c=f.read()) !=-1){
    switch(c){
     case '&':
      if(!marked){
       f.mark(32);
       marked = true;
     }else{
      marked = false;
     }
     break;
     case ';':
      if(marked){
       marked = false;
       System.out.print("(c)");
     }else{
      System.out.print((char)c);
     }
     break;
     case ' ':
      if(marked){
       marked = false;
       f.reset();
       System.out.print("&");
     }else{
      System.out.print((char)c);
     }
     break;
     default:
      if(!marked){
       System.out.print((char)c);
     }
     break;
    }
   }
}
}

 

SequenceInputStream(顺序输入流) 示例

/*
SequenceInputStream类允许连接多个InputStream流。SequenceInputStream的构造不同于任何其他的InputStream。SequenceInputStream构造函数要么使用一对InputStream,要么用InputStream的一个Enumeration,显示如下:
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)
操作上来说,该类满足读取完第一个InputStream后转去读取第二个流的读取要求。使用Enumeration的情况下,它将继续读取所有InputStream流直到最后一个被读完。
text.txt与file2.txt一定要在当前目录下。
*/
//Demonstrate squenced input.
import java.io.*;
import java.util.*;
class InputStreamEnumerator implements Enumeration{
private Enumeration files;
public InputStreamEnumerator(Vector files){
   this.files = files.elements();
}
public boolean hasMoreElements(){
   return files.hasMoreElements();
}
public Object nextElement(){
   try{
    return new FileInputStream(files.nextElement().toString());
   }catch(Exception e){
    return null;
   }
}
}
class SequenceInputStreamDemo{
public static void main(String[] args) throws Exception{
   int c;
   Vector files = new Vector();
   files.addElement("text.txt");
   files.addElement("file2.txt");

   InputStreamEnumerator e = new InputStreamEnumerator(files);
   InputStream input = new SequenceInputStream(e);
   while((c=input.read())!=-1){
    System.out.print((char)c); 
   }
   input.close();
}
}
 
 
FileReader类 示例
 
import java.io.*;
class FileReaderDemo{
public static void main(String[] args) throws Exception{
   FileReader fr = new FileReader("FileReaderDemo.java");
   BufferedReader br = new BufferedReader(fr);
   String s;
   while((s=br.readLine())!=null){
    System.out.println(s);
   }
   fr.close();
}
}
 
 
FileWriter类 示例
 
/*
FileWriter 创建一个可以写文件的Writer 类。它最常用的构造函数如下:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
它们可以引发IOException或SecurityException异常。这里,filePath是文件的完全路径,fileObj是描述该文件的File对象。如果append为true,输出是附加到文件尾的。FileWriter类的创建不依赖于文件存在与否。在创建文件之前,FileWriter将在创建对象时打开它来作为输出。如果你试图打开一个只读文件,将引发一个IOException异常。
*/

// Demonstrate FileWriter.
import java.io.*;
class FileWriterDemo{
public static void main(String[] args) throws Exception {
   String source = "Now is the time for all good men\n"
         + " to come to the aid of their country\n"
         + " and pay their due taxes.";
   char buffer[] = new char[source.length()];
   source.getChars(0, source.length(), buffer, 0);
   FileWriter f0 = new FileWriter("file1.txt");
   for (int i=0; i < buffer.length; i += 2) {
    f0.write(buffer[i]);
   }
   f0.close();
   FileWriter f1 = new FileWriter("file2.txt");
   f1.write(buffer);
   f1.close();
   FileWriter f2 = new FileWriter("file3.txt");
   f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
   f2.close();
}
}

 

 

CharArrayReader类 示例

/*

CharArrayReader 是一个把字符数组作为源的输入流的实现。该类有两个构造函数,每一个都需要一个字符数组提供数据源:
CharArrayReader(char array[ ])
CharArrayReader(char array[ ], int start, int numChars)
这里,array是输入源。第二个构造函数从你的字符数组的子集创建了一个Reader,该子集以start指定的索引开始,长度为numChars。

*/

//Demonstrate CharArrayReader.
import java.io.*;
class CharArrayReaderDemo{
public static void main(String[] args) throws IOException{
   String strTmp = "abcdefghijklmnopqrstuvwxyz"; 
   int intLen = strTmp.length();
   char c[] = new char[intLen];
   strTmp.getChars(0,intLen,c,0);
   CharArrayReader input1 = new CharArrayReader(c);
   CharArrayReader input2 = new CharArrayReader(c,0,5);
   int i;
   System.out.println("input1 is : ");
   while((i=input1.read())!=-1){
    System.out.print((char)i);
   }
   System.out.println();
   System.out.println("input2 is : ");
   while((i=input2.read())!=-1){
    System.out.print((char)i);
   }
   System.out.println();
}
}

 

 

chararraywriter示例

/*

CharArrayWriter 实现了以数组作为目标的输出流。CharArrayWriter 有两个构造函数:
CharArrayWriter( )
CharArrayWriter(int numChars)
第一种形式,创建了一个默认长度的缓冲器。第二种形式,缓冲器长度由numChars指定。缓冲器保存在CharArrayWriter的buf 成员中。缓冲器大小在需要的情况下可以自动增长。缓冲器保持的字符数包含在CharArrayWriter的count 成员中。buf 和count 都是受保护的域。

*/

//Demonstrate CharArrayWriter.
import java.io.*;
class CharArrayWriterDemo{
public static void main(String[] args) throws IOException{
   CharArrayWriter f = new CharArrayWriter();
   String s = "This should end up in the array";
   char buf[] = new char[s.length()];
   s.getChars(0, s.length(), buf, 0);
   f.write(buf);
   System.out.println("Buffer as a string");
   System.out.println(f.toString());
   System.out.println("Into array");
   char c[] = f.toCharArray();
   for(int i=0;i<c.length;i++){
    System.out.print((char)c[i]);
   }
   System.out.println("\nTo a FileWriter()");

   FileWriter f2 = new FileWriter("test.txt");
   f.writeTo(f2);
   f2.close();

   System.out.println("Doing a reset");
   f.reset();
   for (int i=0; i<3; i++)
    f.write('X');
   System.out.println(f.toString());
}
}

 

 

BufferedReader类 示例

/*

BufferedReader 通过缓冲输入提高性能。它有两个构造函数:
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream, int bufSize)
第一种形式创建一个默认缓冲器长度的缓冲字符流。第二种形式,缓冲器长度由bufSize传入。和字节流的情况相同,缓冲一个输入字符流同样提供支持可用缓冲器中流内反向移动的基础。为支持这点, BufferedReader 实现了mark( ) 和reset( ) 方法, 并且BufferedReader.markSupported( ) 返回true.。

*/

// Use buffered input.
import java.io.*;
class BufferedReaderDemo{
public static void main(String[] args) throws IOException{
   String s = "This is a &copy; copyright symbol but this is & copy not.\n";
   char buf[] = new char[s.length()];
   s.getChars(0, s.length(), buf, 0);
   CharArrayReader in = new CharArrayReader(buf);
   BufferedReader f = new BufferedReader(in);
   int c;
   boolean marked = false; 
   while ((c = f.read()) != -1) {
    switch(c) {
     case '&':
     if (!marked) {
      f.mark(32);
      marked = true;
     } else {
      marked = false;
     }
     break;
     case ';':
     if (marked) {
      marked = false;
      System.out.print("(c)");
     } else
      System.out.print((char) c);
     break;

     case ' ':
     if (marked) {
      marked = false;
      f.reset();
      System.out.print("&");
     } else
      System.out.print((char) c);
     break;

     default:
     if (!marked)
      System.out.print((char) c);
     break;
    }
   }
}
}

 

 

流式输入/输出 示例

/*

wc( )方法对任何输入流进行操作并且计算字符数,行数和字数。它在lastNotWhite里追踪字数的奇偶和空格。当在没有参数的情况下执行时,WordCount以System.in为源流生成一个InputStreamReader对象。该流然后被传递到实际计数的 wc( )方法。当在有一个或多个参数的情况下执行时,WordCount 假设这些文件名存在并给每一个文件创建FileReader,传递保存结果的FileReader对象给wc( ) 方法。两种情况下,在退出之前都打印结果。

*/

//A word counting utility.
import java.io.*;
class WordCount{
public static int intWords = 0;
public static int intLines = 0;
public static int intChars = 0;
public static void wc(InputStreamReader isr) throws IOException{
   int c = 0;
   boolean lastWhite = true;
   String whiteSpace = "\t\n\r";
   while((c=isr.read())!=-1){
    //Count characters.
    intChars++;
    //Count lines.
    if(c=='\n'){
     intLines++;
    }
    //Count words by detecting the start of a word
    int intIndex = whiteSpace.indexOf(c);
    if(intIndex == -1){
     if(lastWhite == true){
      ++intWords;
     }
     lastWhite = false;
    }else{
     lastWhite = true;
    }
   }
   if(intChars !=0){
    ++intLines;
   }
}
public static void main(String[] args) 
{
   FileReader fr ;
   try{
    if(args.length ==0){
     //We're working with stdin
     wc(new InputStreamReader(System.in));
    }else{
     //We're working with a list of files.
     for(int i=0;i<args.length;i++){
      fr = new FileReader(args[i]);
      wc(fr);
     }
    }
   }catch(IOException e){
    return;
   }
   System.out.println(intLines + " " + intWords + " " + intChars);
}
}

 

 

Serialization(序列化) 示例

/*

下面的程序说明了怎样实现对象序列化和反序列化。它由实例化一个MyClass类的对象开始。该对象有三个实例变量,它们的类型分别是String,int和double。这是我们希望存储和恢复的信息。

FileOutputStream被创建,引用了一个名为“serial”的文件。为该文件流创建一个ObjectOutputStream。ObjectOutputStream 的writeObject( )方法用来序列化对象。对象的输出流被刷新和关闭。
然后,引用名为“serial”的文件创建一个FileInputStream类并为该文件创建一个ObjectInputStream类。ObjectInputStream 的readObject( )方法用来反序列化对象。然后对象输入流被关闭。
注意MyClass被定义成实现Serializable接口。如果不这样做,将会引发一个NotSerializableException异常。试图做一些把MyClass实例变量声明成transient的实验。那些数据在序列化过程中不被保存

*/

import java.io.*;
class MyClass implements Serializable{
String s;
int i;
double d;
public MyClass (String s,int i,double d){
   this.s = s;
   this.i = i;
   this.d = d;
}
public String toString(){
   return "s=" + s + "; i=" + i + "; d=" + d;
}
}
class SerializationDemo{
public static void main(String[] args){
   //Object serialization.
   try{
    MyClass object1 = new MyClass("Evan",9,9.9e10);
    System.out.println("object1 : " +object1);
    FileOutputStream fos = new FileOutputStream("serial");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(object1);
    oos.flush();
    oos.close();
   }catch(Exception e){
    System.out.println("Exception during serialization :" + e);
    System.exit(0);
   }
   //Object deserialization.
   try{
    MyClass object2 ;
    FileInputStream fis = new FileInputStream("serial");
    ObjectInputStream ois = new ObjectInputStream(fis);
    object2 = (MyClass)ois.readObject();
    ois.close();
    System.out.println("object2 : " +object2);
   }catch(Exception e){
    System.out.println("Exception during serialization :" + e);
    System.exit(0);
   }
}
}

posted @ 2011-11-06 14:04  love25444  阅读(9)  评论(0)    收藏  举报