黑马程序员 IO

---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------
File类
File类是IO包中唯一代表磁盘信息类,而不是文件中的内容。
File类定义了一些与平台无关的方法操纵文件。
Java中的目录被当作一种特殊的文件使用,list方法可以返回目录中的所有子目录和文件名。
在Unix下的路径分隔符(/),Dos下的路径分隔符(/),Java可以正确处理Unix和Dos中的分隔符。

编程举例:
 判断某个文件是否存在,存在则删除,不存在则创建。

package it.heima.io;

import java.io.File;
import java.io.IOException;

public class FileTest {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  File f = new File("1.txt");
  if(f.exists())
  {
   f.delete();
  }
  else
  {
   f.createNewFile();
  }
  System.out.println("File name:" + f.getName());
  System.out.println("File path:" + f.getPath());
  System.out.println("File abs path:" + f.getAbsolutePath());
  System.out.println("File Parent:" + f.getParent());
  System.out.println(f.exists()?"exist":"not exist");
  System.out.println(f.canRead()?"":"");
  System.out.println(f.isDirectory()?"":"");
 }

}

RandomAccessFile类
支持随机访问
善于读取等长格式文件
仅限于操作文件
两种构造方法:
 new RandomAccessFile(f,"rw");读写
 new RandomAccessFile(f,"r");只读

编程实例:
 往文件中写入三名员工的信息,含有姓名和年龄两个字段,然后按照第二,一,三顺序读出信息。
 注意:文件对象调用read()方法读一个字节,readInt()读两个字节。
 
 package it.heima.io;

public class Employee {
 
 public Employee(String name, int age) {
  
  if(name.length() > LEN)
  {
   this.name = name.substring(0, LEN );
  }
  else
  {
   while(name.length() < LEN){
    name += "/u0000";
   }
  }
  this.name = name;
  this.age = age;
 }
 
 public static final int LEN = 8;
 public String name = null;
 public int age = 0;
 
}

package it.heima.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomFileTest {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  Employee e1 = new Employee("张三", 20);
  Employee e2 = new Employee("lisi", 10);
  Employee e3 = new Employee("wangwu", 30);
  
  RandomAccessFile ra = new RandomAccessFile("employee.txt", "rw");
  ra.writeChars(e1.name);
  ra.writeInt(e1.age);
  ra.writeChars(e2.name);
  ra.writeInt(e2.age);
  ra.writeChars(e3.name);
  ra.writeInt(e3.age);
  ra.close();
  
  
  //int len = 0;
  //byte[] buf = new byte[Employee.LEN];
  RandomAccessFile raf = new RandomAccessFile("employee.txt", "r");
  raf.skipBytes(Employee.LEN * 2 + 4);
  //len = raf.read(buf);
  //strName = new String(buf, 0, len);
  String strName = "";
  for(int i = 0; i<Employee.LEN; i++)
  {
   strName += raf.readChar();
  }
  
  System.out.println(strName.trim() + ":" +raf.readInt());
  
  raf.seek(0);
  //len = raf.read(buf);
  //strName = new String(buf, 0, len);
  strName = "";
  for(int i = 0; i<Employee.LEN; i++)
  {
   strName += raf.readChar();
  }
  System.out.println(strName.trim() + ":" +raf.readInt());
  
  raf.skipBytes(Employee.LEN * 2 + 4);
  //len = raf.read(buf);
  //strName = new String(buf, 0, len);
  
  strName = "";
  for(int i = 0; i<Employee.LEN; i++)
  {
   strName += raf.readChar();
  }
  System.out.println(strName.trim() + ":" +raf.readInt());
 }

}

理解流的概念

InputStream类
方法:
 int read() 写入到输入流对象中
 int read(byte[] b)  返回值为读到的字节个数。
 int read(byte[] b, int off, int len)
 long skip(long n) 针对包装类可以跳转
 int available() 检查流中是否有数据,有则读,无则再查,避免阻塞。尽可能多的读取数据。
 void mark(int readlimit)参数从标记位置开始最多能读取的内容。包装类的方法。
 void reset()与mark()配合使用A——B返回到A再读取。
 boolean markSupported()返回当前流是否支持mark,reset方
法。
注意:
 void close()用释放闭操作系统提供的资源,而Java的垃圾回收机制用于回收JVM所产生的资源。

只能处理字节byte。

OutputStream类
方法:
 void write(int b)
 void write(byte[] b)
 void write(byte[] b,int off,int len)
 void flush() 优点:提高CPU使用效率,数据可以修改撤销。缺点:数据滞后。
 void close()

PipedInputStream与PipedOutputStream类

PipedInputStream与PipedOutputStream类用于线程间通信
编程实例:
 package it.heima.io;

import java.io.IOException;
import java.io.PipedOutputStream;

public class Sender extends Thread{
 private PipedOutputStream out = new PipedOutputStream();
 public PipedOutputStream getOutputStream()
 {
  return out;
 }
 public void run()
 {
  String strInfo = new String("hello,receiver");
  try {
   out.write(strInfo.getBytes());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   out.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

package it.heima.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Receiver extends Thread
{
 private PipedInputStream in = new PipedInputStream();
 public PipedInputStream getInputStream()
  {
   return in;
  }
 public void run()
 {   
  byte[] buf = new byte[1024];
  //String strInfo = new String("hello,receiver");
  try {
   int len = in.read(buf);
   System.out.println("the massage from sender");
    new String(buf,0,len);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  try {
   in.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

package it.heima.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedStreamTest {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  Sender t1 = new Sender();
  Receiver t2 = new Receiver();
  
  PipedOutputStream out = t1.getOutputStream();
  PipedInputStream in = t2.getInputStream();
  out.connect(in);
  
  t1.start();
  t2.start();
 }

}

PipedWriter和PipedReader类用于处理字符,使用与上例类似。

ByteArrayInputStream类和ByteArrayOutputStream类。
类似内存虚拟文件,提高访问速度。
构造方法:
 ByteArrayInputStream(byte[] buf)
 ByteArrayInputStream(byte[] buf,int offset,int length)
 ByteArrayOutputStream()创建32个自己的缓冲区。
 ByteArrayOutputStream(int) 创建指定大小的缓冲区,越界后自动增加。

编程实例:
 编写一个函数把英文输入转换为大写存入输入流对象中。
 
package it.heima.io;

import java.io.*;

public class ByteArrayTest {

 /**
  * @param args
  * @throws IOException
  */
 
 public static void transform(InputStream in, OutputStream out) throws IOException
 {
   int ch = 0;
   while((ch = in.read()) != -1)
   {
   int upperCh = Character.toUpperCase((char)ch);
   out.write(upperCh);
   }
 }
 
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  
  String tmp  = "abcdefghijklmnopqrstuvwxyz";
  byte[] src = tmp.getBytes();
  ByteArrayInputStream input = new ByteArrayInputStream(src);
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  transform(input,output);
  byte[]result = output.toByteArray();
  System.out.println(new String(result));
 }

}

重视IO程序代码的复用。

System.in连接到键盘,是InputStream的实例对象。
System.out连接到显示器,是PrintStream类的实例对象。
Windows操作系统用Ctrl+C结束程序。

编程举例:将上例子打印在屏幕上。

package it.heima.io;

import java.io.*;

public class ByteArrayTest {

 /**
  * @param args
  * @throws IOException
  */
 
 public static void transform(InputStream in, OutputStream out) throws IOException
 {
   int ch = 0;
   while((ch = in.read()) != -1)
   {
   int upperCh = Character.toUpperCase((char)ch);
   out.write(upperCh);
   }
 }
 
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  
  String tmp  = "abcdefghijklmnopqrstuvwxyz";
  byte[] src = tmp.getBytes();
  ByteArrayInputStream input = new ByteArrayInputStream(src);
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  transform(input,output);
  byte[]result = output.toByteArray();
  System.out.println(new String(result));
  
  transform(System.in,System.out);
 }

}

 ---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------

详细请查看:<a href="http://edu.csdn.net/heima" target="blank">http://edu.csdn.net/heima</a>


 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值