【问题标题】:PrintWriter not writing to the file but I closed the writer? (java)PrintWriter 没有写入文件,但我关闭了 writer? (爪哇)
【发布时间】:2016-01-17 05:12:21
【问题描述】:

我正在尝试使用 PrintWriter 将一些文本作为输出写入 html 文件,但文本没有保存到文件中。

import java.util.Random;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Creator 
{
static ArrayList<Character> grid = new ArrayList<Character>();
public static void main(String[]args) throws FileNotFoundException
{
    char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

    for(int row=0;row<625;row++)
    {
            grid.add(alphabet[RandGen(0,25)]);
            //System.out.print(grid.get(out));
    }
    Creator.Output();
    System.out.println("Executed.");
}
public static int RandGen(int min, int max)
{
    Random ran = new Random();
    int randomNum = ran.nextInt(max) + min;
    return randomNum;
}
public static void Output()throws FileNotFoundException
{
    //File file=new File("wsm.html");
    //File.createNewFile();
    PrintWriter writer = new PrintWriter("wordsearchmaker.html");
    writer.println("<html>");
    writer.println("<table>");
    writer.println("tr");
    for(int j=0;j<25;j++)
    {
        //for(int k=0;k<25;k++)
    //  {
            System.out.println("<th>"+grid.get(j));
            writer.println("<th>"+grid.get(j));
    //  }

    }
    writer.flush();
    writer.close();

    System.out.println("Outputting...");
}

}

所以我检查了这些方法是否都在运行(因此是“输出...”),并且我 system.out.printed 了我打算写入文件的内容,该文件正在输出什么我想要它。它应该将 html 代码输出到 html 文件(名为 wordsearchmaker.html)中,但没有任何内容保存到文件中。我在网上看到的所有地方都只是说要确保我关闭了作家,我做到了。

注意:我在 eclipse 中工作,这对我来说一直有点挑剔,所以我可能在那里搞砸了?我通常不在 Eclipse 中工作,所以这完全有可能。

【问题讨论】:

  • 文件在那里,但没有任何内容?还是找不到文件?我运行上面的代码,它创建了一个文件,里面有大约 30 行(带有&lt;th&gt; 和其他东西)
  • 我创建了一个文件供它编辑,当我运行它时,文件没有任何变化。
  • 当您创建要编辑的文件时,您很可能正在查看错误的文件。确保提供new PrintWriter("wordsearchmaker.html"); 的完整路径。
  • 我放错了路径,所以我只是创建了一个字符串 var 并将绝对路径设置为它,然后使用它。非常感谢!

标签: java html eclipse printwriter


【解决方案1】:

看起来您已经打开了 PrintWriter,它使您能够将数据发送到文件。但是您实际上并没有打开或创建文件。

尝试先创建一个新文件并对其进行修改:

import java.io.File;

File newFile = new File ("LOCATION OF FILE");

然后,将您的 PrintWriter 设置为使用 newFile。

【讨论】:

  • 不,这没有必要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多