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();
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM