java I/O操作

作为java的初学者,在接触java I/O操作的时候没有一头雾水呢?在进行读文件写文件或者在网络上传输文件的时候有没有一脸疑惑呢?到底什么时候用InputStream什么时候用OutputStream,什么时候read()什么时候write()呢。

现在告诉你,java I/O操作中的in和out(read和write)都是针对内存来说的,就记住,内存内存内存……

这样,我们就可以很容易理解了,当从磁盘读文件到内存,或者从传输流读文件到内存的,就用InputStream\read();从内存写文件到磁盘或写入流中,就用OutputStream\write();

例如:将一个文件在控制台打印出来(这个过程是这样的:从磁盘把读到内存,再从内存中把文件写到控制台;磁盘——>内存——>控制台),那么,我们就可以知道,应该会用到InputStream或read(),然后在OutputStream或write()

  1. public static void readFileByBytes(String fileName) {  
  2.     //创建file对象  
  3.     FileInputStream fileInput = null;  
  4.     try {  
  5.         File file = new File(fileName);  
  6.         if (!file.exists()) {  
  7.             file.createNewFile();  
  8.         }  
  9.         byte[] buffer = new byte[1024];  
  10.         fileInput = new FileInputStream(file);  //就文件放入输入流中
  11.         int byteread = 0;  
  12.         // byteread表示一次读取到buffers中的数量。  
  13.         while ((byteread = fileInput.read(buffer)) != -1) {  //从流中读到内存,边读边到控制台显示
  14.             System.out.write(buffer, 0, byteread);  
  15.         }  
  16.   
  17.     } catch (Exception e) {  
  18.         // TODO: handle exception  
  19.     } finally {  
  20.   
  21.         try {  
  22.             if (fileInput != null) {  
  23.                 fileInput.close();  
  24.             }  
  25.         } catch (IOException e) {  
  26.             // TODO Auto-generated catch block  
  27.             e.printStackTrace();  
  28.         }  
  29.   
  30.     }  
  31.   
  32. }  

  1. public static void readFileByChars(String fileName) {  //
  2.         FileReader reader = null;  //声明一个reader
  3.         try {  
  4.             File file = new File(fileName);  
  5.             if (!file.exists()) {  
  6.                 file.createNewFile();  
  7.             }  
  8.             reader = new FileReader(file);  
  9.             char[] buffer = new char[1024];  //
  10.             int charread = 0;  
  11.             while ((charread = reader.read(buffer)) != -1) {  //通过流读到内存,一边读入内存一边写到控制台显示
  12.                 System.out.print(buffer);  
  13.             }  
  14.         } catch (IOException e) {  
  15.             // TODO: handle exception  
  16.   
  17.         } finally {  
  18.   
  19.             try {  
  20.                 if (reader != null) {  
  21.                     reader.close();  
  22.                 }  
  23.             } catch (IOException e) {  
  24.                 // TODO Auto-generated catch block  
  25.                 e.printStackTrace();  
  26.             }  
  27.         }  
  28.   
  29.     }  
现在向一个文件中写入数据(过程是这样:控制台界面输入——>内存——>磁盘),那么,我们就知道会用到In……\read()到内存然后在out……\write到磁盘
  1. public void writeByFileOutputStream() { 
  2.     FileOutputStream fop = null; // 将信息从内存写到磁盘用到
    File file = null;
    try {
    file = new File("C:/Users/Administrator/Desktop/newfile.txt");
    // if file doesnt exists, then create it
    if (!file.exists()) {
    file.createNewFile();
    }

    Scanner input = new Scanner( System.in );
    String content = input.nextLine();

    // get the content in bytes
    byte[] contentInBytes = content.getBytes();


    fop = new FileOutputStream(file);
    fop.write(contentInBytes);
    fop.flush();
    fop.close();


    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (fop != null) {
    fop.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

      }
    }

再看看网络编程中的文件传输

如服务器端发文件给客户端,那大致过程是这样的:

server:磁盘中读文件到内存,再从内存中将文件写入传输流中

client:从传输流中读文件到内存,再从内存中将文件写到磁盘

这样,我们就可以知道,server应该先用到InputStream/read(),再用OutputStream/write();client也一样

代码:服务器

public class FileServer{

       public static void main(String[] args)throws Exception{

              //创建文件流用来读取文件中的数据

              File file=new File("lishengjie.jpg");

              FileInputStream fos=new FileInputStream(file);

             

              //创建网络服务器接受客户请求

              ServerSocket ss=new ServerSocket(3108);

              Socket client=ss.accept();

             

              //创建网络输出流并提供数据包装器

              OutputStream netOut=client.getOutputStream();

              OutputStream doc=new DataOutputStream(new BufferedOutputStream(netOut));

             

              //创建文件读取缓冲区

              byte[] buf=new byte[2048];

              int num=fos.read(buf);

              while(num!=(-1)){//是否读完文件

                     doc.write(buf,0,num);//把文件数据写出网络缓冲区

                     doc.flush();//刷新缓冲区把数据写往客户端

                     num=fos.read(buf);//继续从文件中读取数据

              }

              fos.close();

              doc.close();

       }

}

客户端:

public class FileClient{

       public static void main(String[] args)throws Exception{

              //使用本地文件系统接受网络数据并存为新文件

              File file=new File("newFile.jpg");

              file.createNewFile();

              RandomAccessFile raf=new RandomAccessFile(file,"rw");

             

              // 通过Socket连接文件服务器

              Socket server=new Socket(InetAddress.getLocalHost(),3108);

             

              //创建网络接受流接受服务器文件数据

              InputStream netIn=server.getInputStream();

              InputStream in=new DataInputStream(new BufferedInputStream(netIn));

             

              //创建缓冲区缓冲网络数据

              byte[] buf=new byte[2048];

              int num=in.read(buf);

             

              while(num!=(-1)){//是否读完所有数据

                     raf.write(buf,0,num);//将数据写往文件

                     raf.skipBytes(num);//顺序写文件字节

                     num=in.read(buf);//继续从网络中读取文件

              }

              in.close();

              raf.close();

       }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值