这是我第一个文件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