文件IO流
首先IO流基本操作步驟
1.實例化對象,參數傳遞目的地(多態)
2.調用方法操作數據
3.關閉流
一、字節輸出流 :(OutputStream),文件通常使用該類的子類FileOutStream,以多態的方法進行操作
>1.構造方法:FileOutputStream(File file)傳遞一個File類對象或者引用FileOutputStream(File file,boolean append)第一個參數傳遞一個File類對象或者引用,第二個參數如果是true,則表示在文件末尾追加內容,而不是寫入文件開始處FileOutputStream(String name)傳入目的地字符串FileOutputStream(String name,boolean)為true則追加2.主要方法:write(byte[ ] b)參數為字節數組write(byte[ ] b,int off,int len)寫入字符串,從off開始,長度為len public class Demo03 {public static void main(String[] args) throws IOException {//創建文件實例File file=new File("G:"+File.separator+"demo.txt");//判斷路徑是否存在,如果不存在,則創建該路徑if(!file.getParentFile().exists())file.getParentFile().mkdirs();//判斷文件是否存在,若不存在,則創建該文件if (!file.exists()) {file.createNewFile();}String bys="\r\nwww.sks";//將bys字符串轉換為字節數組byte[] bytes=bys.getBytes();//int len=bytes.length;//多態,輸出流實例化OutputStream file1 = new FileOutputStream(file,true);//寫入操作file1.write(bytes,0,5);//關閉流file1.close();} }二、字節輸入流(InputStream),文件操作通常使用該子類FileInputStream類來實現
> 1.構造方法FileInputStream(File file)傳入File類對象或者引用FileInputStream(String name)傳入路徑字符串2.主要方法write(byte[ ] b) 讀取b.length個字節write(byte[ ] b,int off,int len)讀取最多len個字節 public class Demo04 {public static void main(String[] args) throws IOException {//創建文件實例File file = new File("G:" + File.separator + "demo.txt");//輸入流實例化FileInputStream fileInputStream = new FileInputStream(file);byte[] bytes = new byte[512];//讀入len個字節到字節數組中去fileInputStream.read(bytes,0,5);//轉換為字符串String content=new String(bytes);System.out.println(content);//關閉流fileInputStream.close();} }三、字符輸出流(Writer) 文件通常使用該子類FileWriter類進行操作
> 1.構造方法FileWriter(File file)參數為File類對象FileWriter(File file ,boolean append)append為true則在文件末尾追加數據FileWriter(String fileName)文件路徑FileWriter(String fileName,boolean append)與上面類似2.主要方法write(char[ ] cbuf)寫入字符數組write(char[ ] cbuf,int off ,int len)寫入字符數組的一部分write(String str)寫入字符串write(String str,int off,int len)寫入字符串的一部分 public class Demo06 {public static void main(String[] args) throws IOException {File file = new File("G:" + File.separator + "demo.txt");FileWriter fileWriter = new FileWriter(file);String s="zms";//轉換為字符串char[] chars =s.toCharArray();fileWriter.write(chars);fileWriter.close();} }四、字符輸入流Reader通常使用該子類FileReader進行操作
> 1.構造方法:FileWriter(File file)參數為File類對象FileWriter(String fileName)文件路徑2.主要方法write(char[ ] cbuf)讀入到字符數組write(char[ ] cbuf,int off ,int len)讀入到字符數組的一部分skip(long n)跳過某字符 public class Demo08 {public static void main(String[] args) throws IOException {File file = new File("G:" + File.separator + "demo.txt");if (!file.getParentFile().exists())file.getParentFile().mkdirs();if (!file.exists()) {file.createNewFile();}FileInputStream stream = new FileInputStream(file);Reader r = new InputStreamReader(stream);char[] chars = new char[124];r.read(chars);String s = new String(chars);System.out.println(s);r.close();stream.close();System.getProperties().list(System.out);} }總結
- 上一篇: 进程和线程的定义和区别
- 下一篇: 文件IO-Properties