【練習】Java中的讀文件,文件的創建,寫文件


前言

大家好,給大家帶來Java中的讀文件,文件的創建,寫文件的概述,希望你們喜歡

示意圖

讀文件

public static void read(String path,String filename){
 try{
  int length=0;
  String str="";
  byte buffer[] = new byte[10];
  FileInputStream fis = new FileInputStream(new File(path,filename));
  while((length=fis.read(buffer,0,buffer.length))!=-1){
  str+=new String(buffer,0,length);
  }
  System.out.println(str);
  fis.close();
  }catch(FileNotFoundException e){
   System.out.println("文件不存在");
   }catch(IOException e){
    e.printStackTrace();
  }
}

文件的創建

public class FileDemo{
 public static void createFolder(String path){
  File folder=new File(path);
  if(folder.exists()){
   System.out.println("文件夾已存在!");
  }else{
   folder.mkdir();
  }
 }
  public static void createFile(String path,String filename){
  File file=new File(path,filename);
  if(file.exists()){
   System.out.println("文件已存在!");
   System.out.println(file.length());
   }else{
    try{
     file.createNewFile();
    }catch(IOException e){
     System.out.println("文件創建失敗");
    }
  }
 }
  public static void main(String[] args){
   FileDemo.createFolder("c:/text");
   FileDemo.createFile("c:/text","1.txt");
  }
}

寫文件

public static void write(String path,String filename){
 try{
  String str="123456789";
  byte b[] = str.getBytes();
  FileOutputStream fos=new FileOutputStream(new File(path,filename));
  fos.write(b);
  }catch(FileNotFoundException e){
   System.out.println("文件不存在");
  }catch(IOException e){
   System.out.println("寫文件失敗");
  }
}

獲取文件的屬性

String getName()

boolean canRead()
boolean canWrite()

boolean exits()

boolean isFile()
boolean isDirectory()
boolean isHidden()

相關知識與技術

boolean mkdir():創建目錄,若成功返回true

boolean createNewFile():創建一個文件

boolean delete():刪除一個文件

Java中流的分類

  • 流的運動方向:分為輸入流和輸出流兩種
  • 流的數據類型:分為字節流和字符流

所有的輸入流類都是抽象類,所有的輸出流類都是抽象類。

字節:InputStream,OutputStream
字符:Reader類,Writer類

從輸入流讀取數據:

FileInputStream vFile=new FileInputStream("File1.dat");
vFile.read();
vFile.close();

輸出流:

FileOutputStream oFile=new FileOutputStream("File2.dat");
oFile.write(vFile.read()):
oFile.close();

如果覺得不錯,那就點個贊吧!❤️

總結

  • 本文講了Java中的讀文件,文件的創建,寫文件,如果您還有更好地理解,歡迎溝通
  • 定位:分享 Android&Java知識點,有興趣可以繼續關注


免責聲明!

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



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