java学习第34天2020/8/8

如果使用Outputream输出数据,不是很方便,所以,Java提供了打印流PrintStream以后只要遇到打印文件,首先考虑使用PrintStream。

 使用PrintStream写入数据

复制代码
import java. io.FileNotFoundExcept ion;
importj ava. io. FileOutputStream;
import java.io. PrintStream;
public class PrintStreamDemo{
    public static void main(String[] args) throws FileNotFoundException {
          PrintStream out = new Printstream (
          new FileOutputStream("D: /Hello.txt")) ;
          //打印布尔类型
          out.println (true) ;
         //打印字符类型
         out.println('A') ;
         //打印double类型
        out.println(10.0) ;
         //打印整型
        out.println(12) ;
         //打印字符串
        out.println("Hello") ;
         //打印对象
        Person p= new Person() ;
        p.setAge (20) ;
        p.setName ("sky");
        out.println(p) ;
        //关闭
        out.close() ;
   }
}

    #long getFilePoint():记录文件指针的当前位置。
    #void seek(long pos):将文件记录指针定位到pos位置。
    RandomAccessFile类的构造函数如下。

public,RandomAccessFile (File file,String mode)throws FileNotFoundException
public RandomAccessFile (String name,String mode)throws FileNotFoundException

使用RandomAccessFile随机读写文件

复制代码
import java. io. IOException; 
import java. io. RandomAccessFile;
public class RandomAccessFileDemo
  public static void main (String[] args) throws IOException {
    //创建对象
    RandomAccessFile acf =new RandomAccessFile ("D: /Hello.txt", "rw");
    //写byte数组
     byte[] b = "Hello Java! !".getBytes() ;
     acf.write(b) ;
    //设置偏移量
   acf.seek(6) ;
   System. out. println("pointer="+acf .getFilePointer()) ;
   byte[] b2="C++" .getBytes() ;
   acf.write (b2) ;
   int len=-1;
   byte[] buf=new byte [1024] ;
   //将偏移量设置成第一个位置
   acf .seek(0) ;
   System. out. println ("pointer "+acf .getFilePointer());
   while( (len=acf . read (buf)) !=-1) {
       String s =new String (buf,0, len) ;
       System. out.println(s) ;
   }
 }
}


二.指针指定
三.例题
posted @ 2020-08-08 21:27  小强哥in  阅读(51)  评论(0)    收藏  举报