我的带有 FileWriter 的 Java 代码不起作用

以下代码似乎不起作用。我想写入某个路径中的文件,但是当我尝试运行此代码时,它不会写入文件。


public static void main(String[] args) {    

    new File("PATH").mkdir();

    File myfile = new File("PATH");

    try {

        String name = "This is my code";

        char[] c = name.toCharArray();

        FileWriter fw = new FileWriter(myfile);

        int k = 0;

        while (k < c.length) {

            fw.write(c[k]);

            k++;    

        }

    } catch (IOException e) {

        System.out.println(e.getMessage());

    }


至尊宝的传说
浏览 188回答 1
1回答

互换的青春

使用 FileWriter 写入文件public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String[] inputs = new String[] {"input-1","input-2","input-3"};&nbsp; &nbsp; &nbsp; &nbsp; File outputFile = new File("output.txt");&nbsp; &nbsp; &nbsp; &nbsp; try(FileWriter writer = new FileWriter(outputFile)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(String input:inputs) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.write(input);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }使用 BufferedWriter 逐行写入文件public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String[] input = new String[] {"input-1","input-2","input-3"};&nbsp; &nbsp; &nbsp; &nbsp; File outputFile = new File("output-buffer.txt");&nbsp; &nbsp; &nbsp; &nbsp; try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(String inputLine:input) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.write(inputLine);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.newLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }从 java7 开始,您可以使用Files来编写String text = "Text to save to file";Files.write(Paths.get("./fileName.txt"), text.getBytes());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java