初學Java IO之使用FileInputStream和FileReader讀取檔案 四十一
阿新 • • 發佈:2018-12-24
import java.io.*;
public class FileInputStreamTest
{
public static void main(String[] args) throws IOException
{
//建立位元組輸入流
FileInputStream fis = new FileInputStream("FileInputStreamTest.java");
//建立一個長度為1024的竹筒
byte[] bbuf = new byte[1024];
//用於儲存實際讀取的位元組數
int hasRead = 0;
//使用迴圈來重複“取水”的過程
while((hasRead = fis.read(bbuf))>0)
{
//取出"竹筒"中(位元組),將位元組陣列轉成字串輸入
System.out.println(new String(bbuf,0,hasRead));
}
fis.close();
}
}
import java.io.*;
public class FileReaderTest
{
public static void main(String[] args) throws IOException
{
FileReader fr = null;
try
{
//建立字元輸入流
fr = new FileReader("FileReaderTest.java");
//建立一個長度為32的"竹筒"
char[] cbuf = new char[32];
//用於儲存實際讀取的字元數
int hasRead = 0;
//使用迴圈來重複“取水”的過程
while((hasRead = fr.read(cbuf))>0)
{
//取出"竹筒"中(位元組),將位元組陣列轉成字串輸入
System.out.println(new String(cbuf,0,hasRead));
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
//關閉檔案輸入流
if(fr != null)
{
fr.close();
}
}
}
}
再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://www.cnblogs.com/captainbed