java-web安全——RandomAccessFile 和 FileSystemProvider文件讀寫

package com.his;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {
	// write your code here
        readfileContent();
        writefileContent();
        writefileContentPath();
        readfileContentPath();
    }

    public static void readfileContentPath(){
        Path p = Paths.get("pathcontent.txt");
        try{
            byte[] bytes = Files.readAllBytes(p);
            System.out.println(new String(bytes));
        }catch (Exception e){
            e.printStackTrace();
        }


    }



    public static void writefileContentPath(){
        Path p = Paths.get("pathcontent.txt");
        String content = "Hello World.";
        try{
            Files.write(p, content.getBytes());
        }catch (Exception e) {e.printStackTrace();}
    }

    public static void writefileContent(){
        try{
            File f =  new File("randomAccessFile.txt");
            String content = "666666";
            RandomAccessFile raf = new RandomAccessFile(f, "rw");
            raf.writeBytes(content);
            raf.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void readfileContent(){
        try{
            File f = new File("randomAccessFile.txt");
            RandomAccessFile raf = new RandomAccessFile(f,"r");
            int a = 0;
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while((a = raf.read(bytes))!=-1){
                out.write(bytes,0, a);
            }
            System.out.println(out);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章