對文件輸入和輸出的操作
獲取文件 java.io.File
File類在創建對象的時候(調用構造方法)必須指定文件路徑名
寫路徑名時/必須是//而用\則只要\。
File類只能查詢文件的信息,但是不能對文件執行其他寫入或讀取操作
File類下的方法:
file.exists()判斷該路徑下的該文件是否存在,返回值爲boolean
file.getAbsolutePath()獲取該文件的絕對路徑
file.isDirectory()判斷是否是文件夾還是目錄
file.mkdir()創建最後一級目錄,返回創建目錄是否成功
file.mkdirs()遞歸創建
file.isFile()返回是否是文件
file.length()返回文件大小,單位是字節
file.list()返回目錄下所有的文件列表
file.getName()返回文件名
file.listFiles()獲取到目錄下的文件列表
IO流分類:輸入流和輸出流
輸入流:字節輸入流和字符輸入流
字節輸入流:FileInputStream
Byte[] b=new Byte[1024];
FileInputStream fis=new FileInputStream(file);
Fis.skip(2);//字節偏移量
Int a=fis.read();//讀到最後不能再讀,返回附一
While(a!=-1){
a=fis.read(b);//將文件內容輸入到b數組中
}
String str =new String(b);//字節字符轉成字符串
字節輸出流:FileOutputStream
FileOutputStream fos=new FileOutputStream(file,true);//true值爲判斷是否在原內容上追加內容而不是覆蓋
字符輸入流:FileReader
字符輸出流:FileWriter
FileReader reader=new FileReader(file);
字節轉字符
輸入流:InputStreamReader
InputStreamReader reader=new InputStreamReader(new FileInputStream(file));//
字符轉字節
直接getbyze
如果需要按行讀,必須要套用一個緩衝器BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Br.readLine();
注意:流使用完需要關閉
當讀取文件是文本文件建議用字符流,
附:文件間複製內容:
public class IOFile {
public static void main(String[] args) {
File file=new File("E://文件.txt");
File file2=new File("E://接受文件.txt");
FileInputStream inputStream=null;
FileOutputStream outputStream=null;
try {
inputStream=new FileInputStream(file);
outputStream=new FileOutputStream(file2);
byte[] buf = new byte[1024];
int b=0;
while((b= inputStream.read(buf))!=-1){
outputStream.write(buf, 0, b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
字節流與字符流的區別在;
傳輸單位不同:字節流以字節爲單位,字符流以兩個字節的Unicode爲單位