JAVA各種讀寫方式總結

Scanner

首先寫一個函數來獲取Scanner對象。

Scanner reader = null;
    try {
      reader = new Scanner(new File(filepath));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    return reader;

然後在讀取文件時,將文件路徑傳入,獲得Scanner對象reader,之後使用reader.nextLine()方法來進行逐行的讀入,如果需要建圖操作,再調用相應類型的圖的構建指令進行對圖的操作。

Buffer

在讀取文件時我們首先寫一個函數來獲取BufferReader對象。

BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(filepath));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    return reader;

然後在讀取文件時,將文件路徑傳入,獲得BufferReader對象reader,之後使用reader.readLine()方法來進行逐行的讀入,如果需要建圖操作,再調用相應類型的圖的構建指令進行對圖的操作。
在寫入文件時我們首先寫一個函數來獲取BufferWriter對象。

BufferedWriter writer = null;
    try {
      writer = new BufferedWriter(new FileWriter(filepath));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return writer;

然後在讀取文件時,將文件路徑傳入,獲得BufferWriter對象writer,之後使用writer.write(String string)方法來進行逐行的寫入,我們修改每個頂點和邊的toString方法,使得符合文件的語法要求,然後我們使用遍歷圖g中的頂點集合和邊集合,調用其toString方法寫入文件。我們也要將GraphName,GraphType,VertexType,EdgeType等參數根據圖的類型進行寫入文件操作。

Nio

在進行文件的讀取時,首先獲得文件的通道:

FileChannel.open(Paths.get(filepath), StandardOpenOption.READ);

之後我們使用ByteBuffer作爲字符的緩衝區,使用temp字節數組用於存儲不完整的行的內容,判斷是否出現了換行符,注意這要區分LF-\n,CR-\r,CRLF-\r\n,這裏判斷\n。如果出現了換行符,將temp中的內容與換行符之前的內容拼接,將換行符之後的內容(去除換行符)存到temp中。如果沒出現換行符,則將內容保存到temp中。
如果需要建圖操作,我們在讀取到一行的內容以後,使用相應類型的圖的構建指令進行對圖的操作。
在進行文件的寫入時,同樣先獲得文件的通道:

FileChannel.open(Paths.get(filepath), StandardOpenOption.WRITE);

我們使用ByteBuffer作爲字符的緩衝區,要將String寫入文件,我們需要先將這個字符串放入字符緩衝區,然後必須要調用buffer的flip方法,(使緩衝區爲一系列新的通道寫入或相對獲取操作做好準備:它將限制設置爲當前位置,然後將位置設置爲0。)再將buffer的內容使用channel.write(buffer)寫入文件。在進行下一次寫入時,需要使用buffer.clear()清空buffer,否則可能因爲緩衝區大小不夠而報錯。
讀文件的代碼示例:

        File file = new File("file1.txt");  
        FileChannel fileChannel = new RandomAccessFile(file,"r").getChannel();  
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);  
        //使用temp字節數組用於存儲不完整的行的內容  
        byte[] temp = new byte[0];  
        while(fileChannel.read(byteBuffer) != -1) {  
            byte[] bs = new byte[byteBuffer.position()];  
            byteBuffer.flip();  
            byteBuffer.get(bs);  
            byteBuffer.clear();  
            int startNum=0;  
            //判斷是否出現了換行符,注意這要區分LF-\n,CR-\r,CRLF-\r\n,這裏判斷\n  
            boolean isNewLine = false;  
            for(int i=0;i < bs.length;i++) {  
                if(bs[i] == 10) {  
                    isNewLine = true;  
                    startNum = i;  
                }  
            }  

            if(isNewLine) {  
                //如果出現了換行符,將temp中的內容與換行符之前的內容拼接  
                byte[] toTemp = new byte[temp.length+startNum];  
                System.arraycopy(temp,0,toTemp,0,temp.length);  
                System.arraycopy(bs,0,toTemp,temp.length,startNum);   
                //將換行符之後的內容(去除換行符)存到temp中  
                temp = new byte[bs.length-startNum-1];  
                System.arraycopy(bs,startNum+1,temp,0,bs.length-startNum-1);  
                //使用return即爲單行讀取,不打開即爲全部讀取  
                //此時Totemp中已經爲讀好的一行。可用System.out.println(new String(toTemp)); 打印出來
//                return;  
            } else {  
                //如果沒出現換行符,則將內容保存到temp中  
                byte[] toTemp = new byte[temp.length + bs.length];  
                System.arraycopy(temp, 0, toTemp, 0, temp.length);  
                System.arraycopy(bs, 0, toTemp, temp.length, bs.length);  
                temp = toTemp;  
            }  
        }

寫文件的代碼示例:

      GraphPoet g;
      FileOutputStream fos = null;
      fos = new FileOutputStream(new File(filepath));
      FileChannel channel = fos.getChannel();
      ByteBuffer buffer = ByteBuffer.allocate(2048);
      String string = "GraphType = \"GraphPoet\"\n";
      buffer.put(string.getBytes());
      buffer.flip(); // 此處必須要調用buffer的flip方法
      channel.write(buffer);
      buffer.clear();
      string = "GraphName = \"" + g.getName() + "\"\n";
      buffer.put(string.getBytes());
      buffer.flip();
      channel.write(buffer);
      buffer.clear();

另一種較爲簡單的方式爲使用Files.readAllLines()函數。返回值爲String數組。

      GraphPoet g = new GraphPoet();
      Path path = Paths.get(filepath);
      for (String line : Files.readAllLines(path)) {
        FileStrategy.creatGraphPoet(line, g);
      }

FileWriter和FileReader

在讀入文件時使用FileReader進行讀入。

       FileReader fr =  new FileReader ("file1.txt");
       BufferedReader br = new BufferedReader (fr);
       String s;
       while ((s = br.readLine() )!=null) {
             System.out.prinln (s);
       }
       fr.close();

在寫入文件時我們首先寫一個函數來獲取FileWriter對象。

    FileWriter writer = null;
    try {
      writer = new FileWriter(filepath);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return writer;

然後在讀取文件時,將文件路徑傳入,獲得FileWriter對象writer,之後使用writer.write(String string)方法來進行逐行的寫入,我們修改每個頂點和邊的toString方法,使得符合文件的語法要求,然後我們使用遍歷圖g中的頂點集合和邊集合,調用其toString方法寫入文件。我們也要將GraphName,GraphType,VertexType,EdgeType等參數根據圖的類型進行寫入文件操作。

參考文獻

Java NIO 讀取文件、寫入文件、讀取寫入混合
https://blog.csdn.net/z69183787/article/details/77101184
使用FileReader和FileWriter讀取寫入文件內容
https://blog.csdn.net/miyuki0424/article/details/307904
Java NIO 按行讀取超大文件
https://blog.csdn.net/strawberrynick/article/details/54949599
Java nio 文件操作 Path,Files類詳解一
https://blog.csdn.net/LuoZheng4698729/article/details/51697648

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