字節流: InputStream 、 OutputStream
1.從硬盤上讀取一個文件內容加載到程序 需要使用輸入流(FileInputStream)
用法
public void testFileInputStream1() throws IOException{
// 1.創建一個File對象
File file = new File("hello.txt");
// 2.創建一個FileInputStream對象(將文件加載到一個輸入流)
FileInputStream fis = new FileInputStream(file);
// 3.調用FileInputStream類的方法,完成對File文件的讀取
// read()方法 讀取文件的一個字節,當執行到文件末尾時,返回-1
// int b = fis.read();
// // 判斷有沒有讀到文件末尾
// while (b!=-1) {
// System.out.print((char)b);
// b = fis.read();
// }
int b;
while ((b = fis.read()) != -1) {
System.out.print((char)b);
}
// 4.關閉相應的流
fis.close();
}
// 使用try-catch處理異常 可以保證流的關閉一定執行
@Test
public void testFileInputStream2() {
FileInputStream fis = null;
try {
File file = new File("Hello.txt");
fis = new FileInputStream(file);
int b;
while ((b=fis.read()) != -1) {
System.out.println((char)b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.讀取到的數據寫入到數組 (len)
public void testFileInputStream3() {
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
// 讀取到的數據寫入到數組
byte[] b = new byte[5];
// 每次讀入byte數組中的字節長度(真實長度)
int len;
while ((len = fis.read(b)) != -1) {
// // 第一種方式
// for (int i = 0; i < len; i++) {
// System.out.print((char)b[i]);
// }
// 第二種方式
// 讀取一個數組,從索引0開始讀,讀取的長度是len
String str = new String(b, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.FileOutputStream(將程序(內存)中的數據持久化到磁盤)
public void testFileOutputStream() {
FileOutputStream fos = null;
try {
// 1.創建一個File對象,指定寫入的文件位置
// 如果指定的文件存在則將原有的文件覆蓋,如果不存在,則創建一個新的文件
File file = new File("hello2.txt");
if (!file.exists()) {
file.createNewFile();
}
// 2.創建一個FileOutputStream對象,將file對象作爲形參傳遞給構造器
fos = new FileOutputStream(file);
// 3.寫入的數據
String str = "I love you forever and yibainian";
// 需要將字符串轉換成byte類型的數組, write(byte[] b)
fos.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 4.關閉輸出流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 實現文件的複製(從硬盤讀取一個文件,並寫入到另外一個位置)
public void copyFile(String src,String dest) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 1.提供讀入,寫出的文件
File file1 = new File(src);
File file2 = new File(dest);
// 2.提供對應的輸入流和輸出流對象
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
// 3.實現文件的複製(先讀數據再寫數據)
byte[] b = new byte[24];
int len;
// 讀取輸入流中的數據
while ((len = fis.read(b)) != -1) {
// 寫數據(從頭開始寫 寫的長度是len)
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 4.關閉相應的輸入流、輸出流
// 最早打開的 最晚關閉
if (fos != null) {
fos.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}