java中创建文件并写入的方法

import java.io.*;

public class CreateFile {
    public static void main(String[] args) {
        String path = "E:\\a\\s";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String writeFilePath = path + "//newFile.txt";
//        File writeFile = new File(path, "newFile.txt");
        File writeFile = new File(writeFilePath);
        if (!writeFile.exists()) {
            try {
                writeFile.createNewFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        String s = "Print from Java!\n";

        try {
            PrintWriter pw = new PrintWriter(new FileWriter(writeFilePath));
//            pw.println(s);
            pw.write(s, 5, s.length() - 5);
            pw.print(s);
            pw.print("Here!");
            pw.flush();
            pw.close();
//            pw.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(writeFilePath)));
//            BufferedReader br = new BufferedReader()
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
posted @ 2019-09-18 21:35  点点爱梦  阅读(3000)  评论(0编辑  收藏  举报