Java文件读写

import java.io.*;

public class Study {
    public static void main(String[] args) {
        try {
            String strPath = "d:\myTest\abc.txt";
            File txtFile = new File(strPath);
            if( !txtFile.exists() ){
                System.out.println("No found text file.");
                System.out.println(txtFile.getPath());
                System.out.println(txtFile.getName());
                System.out.println(txtFile.getParentFile().getPath());
                boolean bMakeDir = txtFile.getParentFile().mkdir();
                System.out.println(bMakeDir);
                System.out.println(txtFile.createNewFile());
            }
            else{
                System.out.println("Yes, the text file already existing.");
            }
            
            String strDir = "D:\myTest";
            File dir = new File(strDir);
            System.out.println(dir.isFile());
            System.out.println(dir.isDirectory());
            
            FileWriter fw = new FileWriter(txtFile);
            fw.write("abcdefg");
            fw.close();
            
            String txt;
            StringBuilder text = new StringBuilder();
            BufferedReader br = new BufferedReader(new FileReader(txtFile));
            while((txt = br.readLine()) != null){
                text.append(txt);
            }
            System.out.println(text);
            
            txtFile.deleteOnExit();
        }
        catch( IOException ex ){    
            ex.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/HD/p/3623188.html