java基礎-輸入流-讀取文本文件中數據至字符串數組


簡介:如題

import java.io.FileInputStream;
/**
 * @author czchina
 *
 */
public class TestStream {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //聲明輸入流的引用
        FileInputStream fls = null;
        //聲明輸出流的引用
        FileOutputStream fos =null;
        try{
            //一、生成代表輸入流的對象
            fls = new FileInputStream("E:/Android/AndroidStudioProjects/text.txt");
            //生成一個字節數組
            byte [] buffer= new byte [100];
            //調用輸入流對象的read方法,讀取數據(將讀出來的長度為<buffer.length-5>的數據放入buffer數組中,5是開始存放的位置)
            //注意讀出來的數據長度不要超過數組長度。
            int num = fls.read(buffer,5,buffer.length-5);
            System.out.println("1、從輸入流讀出的字節數:\n"+num);//看看從輸入流中讀取了多少數據
            
            String s = new String(buffer);
            System.out.println("2、buffer to string, and print: \n"+s);
            //調用一個String對象的trim方法,會去掉字符串的首尾空格,測試如下
            s = s.trim();
            System.out.println("3、String對象調用其trim方法后,print:\n"+s);
        }
        catch(Exception e){
            System.out.println(e.toString());
        }
    }
}

text.txt

image

console:

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM