java讀取文件


public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        StringBuffer sb=new StringBuffer();
        try {

            if(file.isFile() && file.exists()){ //判斷文件是否存在
                System.out.println("以字節為單位讀取文件內容,一次讀多個字節:");
                // 一次讀多個字節
                byte[] tempbytes = new byte[1024];
                int byteread = 0;
                in = new FileInputStream(file);
                ReadFromFile.showAvailableBytes(in);
                // 讀入多個字節到字節數組中,byteread為一次讀入的字節數
                while ((byteread = in.read(tempbytes)) != -1) {
                  //  System.out.write(tempbytes, 0, byteread);
                    String str=new String(tempbytes,0,byteread);
                    sb.append(str);
                }
            }else{
                System.out.println("找不到指定的文件,請確認文件路徑是否正確");
            }


            String data = sb.toString() ;

          } catch (Exception e) {
            System.out.println("讀取文件內容出錯");
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
}
   

/**
* 顯示輸入流中的字節數
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("當前字節輸入流中的字節數為:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

// String fileName = "D:/file/test3.json";
String fileName = "D:/file/1.json";
readFileByBytes(fileName);


}
 
        

 


免責聲明!

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



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