javaSE学习笔记之IO

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014070705/article/details/46766275


File 类:

•java.io包中的File类提供了与具体平台无关的方式来描述目录和文件对象的属性功能。其中包含大量的方法可用来获取路径、目录和文件的相关信息,并对它们进行创建、删除、改名等管理工作。因为不同的系统平台,对文件路径的描述不尽相同。为做到平台无关,在Java语言中,使用抽象路径等概念。Java自动进行不同系统平台的文件路径描述与抽象文件路径之间的转换。

• File类的直接父类是Object类。

• 下面的构造方法可以用来生成File 对象:

File(String directoryPath)

File(String directoryPath, String filename)

File(File dirObj, String filename)

这里,directoryPath是文件的路径名,filename是文件名,dirObj 是一个指定目录的File 对象

这些构造方法取决于访问文件的方式。例如,若在应用程序里只用一个文件,第一种创建文件的结构是最容易的。但若在同一目录里打开数个文件,则后种方法更好一些。

public class FileTest
{
         publicstatic void main(String[] args) throws IOException
         {
                   Filefile = new File("c:/abc");             
                   Filefile2 = new File("c:/abc", "xyz/hello.txt");            
                   file2.createNewFile();
         }
}


• 目录管理

目录操作的主要方法为:

– public  boolean ) mkdir()  根据抽象路径名创建目录。

–  public ] String[] ) list()  返回抽象路径名表示路径中

的文件名和目录名 。

• 文件管理

– 在进行文件操作时,常需要知道一个关于文件的信息。Jave的File类提供了方法来操纵文件和获得一个文件的信息。另外,File类还可以对目录和文件进行删除、属性修改等管理工作

public class FileTest
{
	public static void deleteAll(File file)
	{
		if(file.isFile() || file.list().length == 0)
		{
			file.delete();
		}
		else
		{
			File[] files = file.listFiles();
			
			for(File f : files)
			{
				deleteAll(f);
				
				f.delete();
			}
		}
	}
	
	
	public static void main(String[] args)
	{
		deleteAll(new File("c:\\java"));
	}
}

IO流:

Jdk所提供的所有流类型位于包java.io内都分别继承自以下四种抽象流类型:

  字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

1.InputStream:继承自InputStream的流都是用于向程序中输入数据,且数据的单位为字节:

InputStream的基本方法:

int  read()//读取一个字节并以整数的形式返回(0~255),如果返回-1表示已到输入 流的末尾。

 int  read(byte[] buffer)//读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1

int read(byte[] buffer,int offer,int length)//读取length个字节,并存储到一个字节数组buffer,从length位置开始,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1

void close()//关闭流释放内存资源

long skip (long n)//跳过n个字节不读,返回实际的字节数

TestFileInputStream {
  public static void main(String[] args) {
    int b = 0;
    FileInputStream in = null;
    try {
      in = new FileInputStream("d:\io\TestFileInputStream.java");
    } catch (FileNotFoundException e) {
      System.out.println("找不到指定文件"); 
      System.exit(-1);
    }
    
    try {
      long num = 0;
      while((b=in.read())!=-1){
        System.out.print((char)b); 
        num++;
      }
      in.close();  
      System.out.println();
      System.out.println("共读取了 "+num+" 个字节");
    } catch (IOException e1) {
      System.out.println("文件读取错误"); System.exit(-1);
    }
  }
}

2.OutputStream:继承自OutputStream的流是用于程序中输入数据,且数据的单位为字节:

OutputStream的基本方法:

Void write (int b)//向输入流中写入一个字节数据,该字节数据为参数b的低8位

Void write(byte[] b)//将一个字节类型的数组中的数据写入输出流

Void write(byte[] b,int off,intlen)//将一个字节类型的数组中的从指定位置(off)开始的len个字节写入到输出流

void close()//关闭流释放内存资源

Void flush()//将输出流中缓存的数据全部写到目的地

public class TestFileOutputStream {
  public static void main(String[] args) {
	  int b = 0;
	  FileInputStream in = null;
	  FileOutputStream out = null;
	  try {
	    in = new FileInputStream("d:/HelloWorld.java");
	    out = new FileOutputStream("d:/io/Hello.java");
	    while((b=in.read())!=-1){
	      out.write(b);
	    }
	    in.close(); 
	    out.close();
	  } catch (FileNotFoundException e2) {
	    System.out.println("找不到指定文件"); System.exit(-1);
	  } catch (IOException e1) {
	    System.out.println("文件复制错误"); System.exit(-1);
	  }
	  System.out.println("文件已复制");
  }
}



3.Reader:继承自Reader流的都是用于向程序中输入数据,且数据单位为字符。
Reader的基本方法:
int  read()//读取一个字符并以整数的形式返回(0~255),如果返回-1表示已到输入流的末尾。
int  read(byte[] buffer)//读取一系列字符并存储到一个数组buffer,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1
int  read(byte[] buffer,int offer,int length)//读取length个字符,并存储到一个字节数组buffer,从length位置开始,返回实际读取的字符数,如果读取前已到输入流的末尾返回-1
void close()//关闭流释放内存资源

long skip (long n)//跳过n个字符不读,返回实际的字符数

public class TestFileReader {
  public static void main(String[] args) {
    FileReader fr = null; 
    int c = 0;
    try {
      fr = new FileReader("d:\\io\\TestFileReader.java");
      int ln = 0;
      while ((c = fr.read()) != -1) {
        //char ch = (char) fr.read();
        System.out.print((char)c);
        //if (++ln >= 100) { System.out.println(); ln = 0;}
      }
      fr.close();
    } catch (FileNotFoundException e) {
      System.out.println("找不到指定文件");
    } catch (IOException e) {
      System.out.println("文件读取错误");
    }

  }
}



4.Writer:继承自Writer的流都是用于程序中输入数据,且数据单的单位为字符
Writer的基本方法
Void write (int c)//向输入流中写入一个字符数据,该字符数据为参数c的低16位
Void write(char[] c)//将一个字符类型的数组中的数据写入输出流
Void write(char[] b,int off,int len)//将一个字符类型的数组中的从指定位置(off)开始的len个字符写入到输出流
void writer(String string)//将一个字符串的字符写入到输入流
void writer(String string,int offset,int length) //将一个字符串从offset开始的length个字符写入到输出流
void close()//关闭流释放内存资源
void flush()//将输出流中缓存的数据全部写到目的地

public class TestFileWriter {
  public static void main(String[] args) {
    FileWriter fw = null;
    try {
      fw = new FileWriter("d:\\unicode.dat");
      for(int c=0;c<=50000;c++){
        fw.write(c);
      }
      fw.close();
    } catch (IOException e1) {
    	e1.printStackTrace();
      System.out.println("文件写入错误");
      System.exit(-1);
    }
  }
}



5.缓冲流:减少磁盘的读写次数
BufferInputStream、BufferOutputStream、BufferReader、BufferWriter
其构造方法为:
BufferInputStream(InputStream in)
BufferInputStream(InputStream in,int size)//sz为自定义缓存区的大小
BufferOutputStream(OutputStream out)
BufferOutputStream(OutputStream out,int size)
BufferReader(Reader in )
BufferReader(Reader in,int size)
BufferWriter(Writer out)
BufferWriter(Writer out,int size)

注意:
BufferReader提供readLine方法用于读取一行字符串(以\r或\n分隔)
BufferWriter提供newLine用于写入一个行分隔符
对于输出的缓冲流,写出的数据会现在内存中缓存,使用flush方法将会使内存中的数据立刻出来

public class TestBufferStream2 {
  public static void main(String[] args) {
    try {
      BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\java\\dat2.txt"));
      BufferedReader br = new BufferedReader(
             new FileReader("d:\\java\\dat2.txt"));
      String s = null;
      for(int i=1;i<=100;i++){
        s = String.valueOf(Math.random());
        bw.write(s);
        bw.newLine();
      }
      bw.flush();
      while((s=br.readLine())!=null){
        System.out.println(s);
      }
      bw.close(); 
      br.close();
    } catch (IOException e) { e.printStackTrace();}
  }
}


6.Object流:ObjectInputStream 和ObjectOutputStream需要实现serializable接口实现序列化
序列化:序列化只能保存对象的非ststic成员,不能保存任何成员方法和static成员变量,而且序列化保存的只是变量的值;
用transient关键字修饰的变量为临时变量,不能被序列化;
当成员变量为引用类型时,引用的对象也被序列化。

public class TestObjectIO {
	public static void main(String args[]) throws Exception {
		T t = new T();
		t.k = 8;
		FileOutputStream fos = new FileOutputStream("d:/java/io/testobjectio.dat");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(t);
		oos.flush();
		oos.close();
		
		FileInputStream fis = new FileInputStream("d:/java/io/testobjectio.dat");
		ObjectInputStream ois = new ObjectInputStream(fis);
		T tReaded = (T)ois.readObject();
		System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);
		
	}
}

class T implements Serializable
{
	int i = 10;
	int j = 9;
	double d = 2.3;
	transient int k = 15;
}


7.文件复制代码:

public class FileCopy {
  public static void main(String[] args) {
	  int b = 0;
	  FileReader in = null;
	  FileWriter out = null;
	  try {
	    in = new FileReader("f:/a.txt");
	    out = new FileWriter("f:/b.txt");
	    while((b=in.read())!=-1){
	      out.write(b);
	    }
	    out.close();
	    in.close(); 
	    
	  } catch (FileNotFoundException e2) {
	    System.out.println("找不到指定文件"); System.exit(-1);
	  } catch (IOException e1) {
	    System.out.println("文件复制错误"); System.exit(-1);
	  }finally{
		  try {
			  if(out != null)
			   out.close();
			  if(in != null)
			     in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		    
	  }
	  System.out.println("文件已复制");
  }
}



猜你喜欢

转载自blog.csdn.net/u014070705/article/details/46766275
今日推荐