输入输出流

 

Java的输入输出功能必须借助于输入输出类库Java.io包来实现,这个包中的类大部分是用来完成流式输入输出的流类。

在java中,把能够读取一个字节序列的对象称为一个输入流,把能够写一个字节的对象称为一个输出流。分别由

InputStream和OutputStream表示。

 

处理Unicode码的字符流,由抽象类Reader(输入)和Writer(输出)派生。

 

流是指在计算机的输入与输出之间的数据的序列,而Java中的数据流有位流(字节流)和字符流之分;

 

就流的运动方向而言,流可分为输入流(input stream)和输出流(output stream),输入流代表从外设流入计算机的数据序列;输出流代表从计算机流向外设的数据序列。

 

java.io包通过数据流、序列和文件系统为系统提供输入输出。

 

InputStream类的实现:
  public abstract class InputStream extends Object
InputStream类的方法
  public int available() throws IOException
   返回目前输入数据流中已有几个字符准备好被读取了.
  public void close()throws IOException
   将这个输入数据流关闭
  public abstract int read()throws IOException
   从输入数据流读取下一个字节并返回.返回值的范围从0到255,但如果已经到达数据流的结尾,没有数据可以读取了,则会返回-1.抛出异常

 

public int read(byte[] b)throws IOException
  从输入数据流中读取数个字节放进数组b中,并返回所读取到的字符数目,最多可以读取和b长度相同的字符数,但如果没有读取到则返回-1
    public long skip(long n)throws IOException
       略过n个字节不读取,会返回实际略过的字节数目.因为数据流中剩下的数据可能不到n个字节那么多,所以此时返回值会小于n

 


InputStream类的继承关系

       InputStream
     FileInputStream(文件输入字节)
     FilterInputStream
          DataInputStream(格式转换)
           BufferedInputStream (缓冲功能)

 

 

标准输入——System.in

 

  System.in是System的一个静态属性,属于InputStream类对象,用于输入字节数据流,对应标准输入设备:键盘。

 

 

Java实例——标准输入
   import java.io.*;
   public class StandardIn1
  {   public static void main(String[] args) throws IOException
    {    char c;
         System.out.println(" 输入一个字符");
         c=(char)System.in.read(); 
         System.out.print( "输入的字符是:"+c);    }
     }

 

 

 

OutputStream类

 

      OutputStream类是所有输出数据流的父类,所以它也被实现成抽象类,定义了所有输出数据流都具有的共同特性.
      OutputStream类的实现:
      public abstract class OutputStream extends Object

 

OutputStream类的继承关系

  OutputStream
       FileOutputStream(文件输出)
       FilterOutputStream
             PrintStream(输出到屏幕)
             DataOutputStream(格式转换)
             BufferedOutputStream (缓冲功能)

 

OutputStream类的method

    public void close( ) throws IOException
 关闭与输出数据流的连系
 public void flush( )throws IOException
 将写入的数据确实送到接受数据的装置去.因为写入的数据通常会先放到高速缓存(cache)里面,等到数量达到某一程度时,用这个方法将强迫数据写进去.
 public void write(byte[ ] b)throws IOException 
 将数组b中的数据写入输出数据流

 

public void write(byte[] b,int off,int len)throws IOException
    将b数组中从第off个字节开始,共写入len个字节到输出数据流
public abstract void write(int b) throws IOException
    写入一个字符到输出数据流.这个method只会将b的8个低位写入,将24个高位忽略掉.

 

 

标准输出——System.out

 System.out是它的一个静态属性,属于PrintStream类对象,用于输出字节数据流,对应标准输出设备:屏幕。

 

 

 File类

  File类指的是磁盘上的目录或文件.“//”表示分隔符。例如:D://myjava//Hello.java

 

文件类的主要方法:

 public File(File parent,String child):建立一个以parent加上child为路径的File组件。
 public File(String pathname):建立一个以pathname为路径的File组件   
 public String getName():得到文件的名字
 public String getPath():得到文件的路径名
 public String getParent():得到文件的上级路径名
 public boolean exists():判断文件或目录是否存在
 public long length():返回文件的字节数
 public boolean createNewFile() throws IOException:以File组件的内容为文件名建立一个新文件,如果原文件已存在,返回false,如果建  立成功,则返回true.
 public void delete():删除文件

 

 

RandomAccessFile类

RandomAccessFile流由于实现了DataInput和DataOutput两个接口,所以既可以用来处理文件的输入,又可以处理文件的输出。
主要方法:
 public RandomAccessFile(String name,String mode)构造RandomAccessFile流对文件进行读写。name为文件名, mode为读写模式,包 括r(只读)/rw(可读写).

 

 close( )关闭RandomAccessFile流,并释放资源。
 getFilePointer()返回文件指针位置。
 length()返回文件长度
 read()从文件中读取一个字节的数据
 readInt()从文件中读取一个int值(4个字节)
 readLine()读取一行
 seek(long pos)定位参数pos在文件中指定的位置.

skipBytes():在文件中跳过指定数量的字节,数量由n指定。
writeChars(String s):向文件写入一个作为字符数据的字符串。
writeInt():向文件写入一个int型数据。

 


Reader类

 

Reader子类的继承关系


 Reader
    BufferedReader(缓冲功能的字符输入类)
         InputStreamReader(输入字节转换为字符) 
               FileReader (从文件读入字符)

 

Writer类的method

 

public abstract void close()throws IOException
关闭与输出数据流的连接,但关闭之前会先调用一次flush method.如果程序结束前没有调用这个method.则写入的数据可能会流失调.
 public abstract void flush()throws IOEception
将写入的数据确实送到收据的装置去.
 public void write(char[] cbuf)
将cbuf数组中的字符一一 写入输出数据流

 

public void write(char[] cbuf,int off,int len)
将cbuf数组中从第off个字符开始,共写入len个字符到输出数据流.
public void write(String str)
写入一个字符串到输出数据流

 

二、标准输入输出

 

Java系统预先定义好3个流对象分别表示标准输出设备、标准输入设备和标准错误设备,它们分别是System.out,System.in和System.err。

 

 System.out是它的一个静态属性,属于PrintStream类对象,用于输出字节数据流,对应标准输出设备:屏幕。
 System.in 也是System的一个静态属性,属于InputStream类对象,用于输入字节数据流,对应标准输入设备:键盘。
 System.err 也是System的一个静态属性,属于PrintStream类对象,用于系统错误信息的输出,对应屏幕。

 

 

 

例:输入字符串

 

可以利用BufferedReader类的readLine()方法从键盘输入字符串,该方法一次读入一行字符串,即按回车键前面输入的所有字符,同时具备缓冲功能,提高运行效率。
输入字节——转化为字符——具有缓冲功能的输入字符
InputStream(System.in) ——InputStreamReader(iin)—— BufferedReader(bin)

 

 

Import java.io.*;
Public class Standardin3
{public static void main(String args[]) throws IOException{ 
InputStreamReader iin=new InputStreamReader(System.in);
   BufferedReader bin=new BufferedReader(iin);
   String s;   float f;   int i;   Boolean b;
   System.out.println(“请输入任一字符串”);
   S=bin.readLine();
   System.out.println(“请输入浮点数”);
   f=Float.parseFloat(bin.readLine());
   System.out.println(“输入整数”);
   i=Integer.parseInt(bin.readLine());
   System.out.println(“输入布尔变量”);
   b=new Boolean(bin.readLine()).booleanValue();
   System.out.println(“输入的字符串:”+s);
   System.out.println(“输入的浮点数:”+f);
   System.out.println(“输入的整数:”+i);
   System.out.println(“输入的布尔变量:”+b);       }    }

 


标准输出

 

Java的标准输入设备:显示器用System.out表示,System.out属于PrintStream类对象。
    利用PrintStream类的print()或println()方法可以非常方便地输出各类数据,这两个方法的唯一区别是print()输出后不换行,而println()方法输出完毕后要换行 。


三、文件操作

在程序中要对磁盘文件或目录进行操作,首先要对文件或目录建立连接,为此Java提供了File类。File类也位于java.io包中,但不是流类,而是专门用来管理磁盘文件和目录。
     一个File类对象表示一个磁盘文件或目录,其对象属性中包含了文件或目录的相关信息,如名称、长度、所含文件个数等,其方法可以完成对文件或目录的常用管理操作,如创建、删除等。

 

 

File类提供了3个不同的构造方法 :
File(String path)
     String类参数path指定所建对象对应的磁盘文件名或目录名及其路径名。
File(String path, String name)
    此构造方法中的参数path表示文件或目录的路径,参数name表示文件或目录名。
 File(File dir, String name)
    此构造方法中的参数dir表示一个磁盘目录对应的File对象,参数name表示文件名或目录名。

 

 

FileOutputStream流类的构造方法有两个:
       FileOutputStream(String fileName):参数fileName表示带路径的磁盘文件名。
       FileOutputStream(File file):参数file表示为磁盘文件所建立的File对象名

 

package com.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class File2 {

    public static void main(String[] args) {

        char ch;
        File file = new File("/home/newFile.txt");
       
        try {
            FileOutputStream fom = new FileOutputStream(file);
            System.out.println("please input a string , end with ?");

            ch = (char) System.in.read();
            while (ch != '?') {
                fom.write(ch);
                ch = (char) System.in.read();

            }
            fom.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

 

 


FileInputStream类流

 

 

FileInputStream流类的构造方法有两个:
       FileInputStream(String fileName):参数fileName表示带路径的磁盘文件名。
       FileInputStream(File file):参数file表示为磁盘文件所建立的File对象名 。

 

 

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class File1 {
   
   
    public static void  main (String[] args) throws IOException {
       
        File  file  = new File ("/home/newFile.txt");
        FileInputStream fim = new FileInputStream(file);
        InputStreamReader inr = new InputStreamReader(fim);
        BufferedReader bf = new BufferedReader(inr);
        System.out.println("the chars is :");
       
       
        while(bf.read() != -1){
           
            System.out.println(bf.readLine());
           
        }
        fim.close();
       
    }

 

 

DataOutputStream

 

 

使用DataOutputStream类向文件中写入各种类型数据的操作步骤是:
为磁盘文件建立File类对象;
为该File对象建立FileOutputStream类流对象,建立其与磁盘文件的连接;
为该FileOutputStream类对象建立DataOutputStream类对象,利用DataOutputStream类的writeInt(),writeFloat(),writeDouble(),writeBoolean()等方法分别向文件中写入整型、单精度型、双精度型、布尔型等数据;
写入操作完成后,利用close()方法将流关闭,断开与磁盘文件的联系。 

 

 

import java.io.*;
public class File4
  {
   public static void main(String[] args)
    {
int ch;
InputStreamReader iin=new InputStreamReader(System.in);
BufferedReader bin =new BufferedReader(iin);
File file1=new File("c://jdk1.3//example//dataFile.txt");
try
{
FileOutputStream fout= new FileOutputStream(file1);
DataOutputStream dout =new DataOutputStream(fout);
System.out.println(" 输入整数");
int i=Integer.parseInt(bin.readLine());
     System.out.println(" 输入浮点数");

float f=Float.parseFloat(bin.readLine());
System.out.println(" 输入布尔量");
boolean b=new Boolean(bin.readLine()).booleanValue();
dout.writeInt(i);
dout.writeFloat(f);
dout.writeBoolean(b);
dout.close();
    }
catch (FileNotFoundException e)
      { System.out.println(e);}
catch (IOException e)
{  System.out.println(e);}
}
}

 

 

DataInputStream类流

 

 

从磁盘文件中读入各类数据.
本程序的功能是将磁盘文件dataFile.txt中保存的各类数据复制到磁盘文件outFile.txt中.

 

Import java.io.*;
public class File5 {
   public static void main(String[] args) throws IOException
  {  int ch;
     File file1=new File(“c://…//dataFile.txt”);
     File file2=new File(“c://…//outFile.txt”);
     try  {
        FileInputStream fin=new FileInputStream(file1);
        DataInputStream din=new DataInputStream(fin);
        int i=din.readInt( );
        float f=din.readFloat();
        boolean b=din.readBoolean();
        din.close();
        FileOutputStream fout=new FileOutputStream(file2);
        DataOutputStream dout=new DataOutputStream(fout);

dout.writeInt(i);
  dout.writeFloat(f);
  dout.writeBoolean(b);
  dout.close();
  System.out.println(“整数:”+ i);
  System.out.println(“浮点数:”+f);
  System.out.println(“布尔量:”+b);
}
Catch(FileNotFoundException e)
  {     System.out.println(e);     }
Catch(IOException e)
  {     ystem.out.println(e);       }
}
}

 

 

Writer和Reader

 

 

以字符流方式向文件写入或从文件中读取数据,可以使用Writer和Reader类及其子类。
Writer和Reader类都是抽象类,不能建立它们的对象,所以只能通过它们子类对象对文件进行操作。常用的Writer类的子类包括FileWriter类和BufferedFileWriter类。
FileWriter类构造方法如下:
         FileWriter(String fileName):参数fileName表示带路径的磁盘文件名。                     
         FileWriter(File file): 参数file表示为磁盘文件所建立的File对象名。  
   注:使用FileWriter进行文件操作时,为了减少和磁盘打交道的次数,常常使用具有缓冲功能的BufferedWriter类。

 

 

import java.io.*;
public class File8 {
  public static void main(String args[]) throws Exception {
   InputStreamReader iin =new InputStreamReader(System.in);
   BufferedReader br=new BufferedReader(iin);
   FileWriter fw1=new FileWriter("c://jdk1.3//example//dataFile.txt");
   BufferedWriter bw = new BufferedWriter(fw1);
   String s;
   while (true){
      System.out.print("输入一个字符串:");
      System.out.flush();
      s=br.readLine();
      if (s.length()==0) break;
      bw. write(s);
      bw.newLine();
      }
    bw.close();
    }
  }

 

 

 

import java.io.*;
public class File9 {
  Public static void main(String args[]) throws Exception
  {  FileReader fr1=new FileReader(“c://…// dataFile.txt”);
     Bufferedreader br1=new BufferedReader(fr1);
     Bufferedreader bw1=new
       BufferedWriter(new FileWriter(“c:// …//targetFile.txt”);
     Int lineNum=0;
     String s=br1.readLine();
     While(s!=null) {
         lineNum++;
         bw1.write(String.valueOf(lineNum));
         bw1.write(“  ”);
         bw1.write(s);
         bw1.newLine();
         s=br1.readLine();
       }
     bw1.close();  }
 }


 

 

 

 

你可能感兴趣的:(String,File,Class,import,磁盘)