FileTest

这是我第一个文件File 相关类的测试例子,分为两部分:MyFirstIOFile 和MyFirstRAFile

1。MyFirstIOFile

import java.io.*;

class MyFirstIOFile {
  public static void main(String[] args){
    char ch = ' ';
    System.out.println("plz input some characters.");     
    try{
      FileOutputStream my_outfile = new FileOutputStream("..//myfile.txt");
      while( (ch=(char)System.in.read()) != '#' ){
        my_outfile.write(ch);
      }
      my_outfile.close();
    }catch(IOException e){};

    System.out.println("show the file characters:");
    try{
      FileInputStream my_infile = new FileInputStream("..//myfile.txt");
      //byte[] k = {}; 错误:这种所谓动态分配无法读取文件中的字节。
      byte[] k = new byte[20];
      my_infile.read(k);
      System.out.write(k);
      my_infile.close();
    }catch(FileNotFoundException e){}
    catch(IOException e){};
  }
 
}

2。MyFirstRAFile

//由于 RandomAccessFile(String/File, String mode)的第二个参数有两种情况:rw(写) 和r(读)
//所以在RandomAccessFile 对象进行写入或者读取的时候就要区分开来,必须要定义两个不同的对象!
//下面的my_rafile 和my_rafile_r 才能分别准确使用RandomAccessFile 对象自带的写入和读取的方法。

import java.io.*;
//import java.lang.*;
//import java.util.*;

class MyFirstRAFile{
  public static void main(String[] args){
    //String test = new String("Longtest");
    //long ml = Long.parseLong("ewt");
    //Long my_Long = new Long(test);
    //long my_long = my_Long.longValue();
    //String ms = my_Long.toString();
    //System.out.println(my_Long);
    RandomAccessFile my_rafile = null;
    try{
    my_rafile = new RandomAccessFile("..//myfile.txt","rw");
    for(int i=0;i<10;i++)
      my_rafile.writeBytes("RandomAccessFile Test Line:" + i + "/r/n");
    //my_rafile.close();
    }catch(FileNotFoundException e){}
    catch(IOException e){};
   
    try{
    //my_rafile = new RandomAccessFile("..//myfile.txt","rw");
    my_rafile.seek(my_rafile.length());
    my_rafile.writeBytes("append line /r/n");
    my_rafile.close();
    }catch(FileNotFoundException e){}
    catch(IOException e){};

    try{
    RandomAccessFile my_rafile_r = new RandomAccessFile("..//myfile.txt","r");
    String record = "";
    int i = 0;
    while((record = my_rafile_r.readLine()) != null){
      i++;
      System.out.println("Value "+ i + ":" + record);
    }
    my_rafile_r.close();
    }catch(IOException e){};
       

  }//main
}//class

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值