0

我制作了一个程序来生成一个包含数字的文件但是该程序没有在它创建的文件中输入任何内容!

这是代码:

     private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {                                         
    ModFile=new File(NameText.getText() + ".mod");
    FileWriter writer = null;
    try {
        writer = new FileWriter(ModFile);
    } catch (IOException ex) {
        Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
    }
   if(!ModFile.exists()){
   try {
   ModFile.createNewFile();
   System.out.println("Mod file has been created to the current directory");
   writer.write(CodesBox.getText());
   } catch (IOException ex) {
   Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
       }
     }     
   }                      

当我创建一个随机文件时,我打开它时看不到任何东西!请帮助
感谢 Amir 的帮助,但我注意到我应该使用 FileOutputStream 和 DataOutputStream ......
所以,我需要帮助再次导致出现同样的问题:(

 File ModFile =new File(NameText.getText() + ".mod");
try {
    FileOutputStream fos = new FileOutputStream(ModFile);
    DataOutputStream dos = new DataOutputStream(fos);
    int i = Integer.parseInt(CodesBox.getText());
    dos.writeInt(i);
        // and other processing 
} catch (IOException ex) {
    Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
    try{
         dos.close();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

NetBeans 说他们在 (dos.close();) 处找不到符号 dos

请再次帮助我

4

1 回答 1

0
  • 您必须检查文件名是否存在于NameText.getText().
  • 您不需要创建文件,如果文件不存在 FileWriter 将自行创建。
  • 您应该在处理后关闭文件

    私人无效OpenMenuActionPerformed(java.awt.event.ActionEvent evt){

        //check before file name is nt null
        File ModFile =new File("somefile" + ".mod");
        FileWriter writer = null;
    
        try {
            writer = new FileWriter(ModFile);
            writer.write("test..................");
                // and other processing 
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }                    
    

++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++使用FileOutputStream和写字节阵列遵循下面的代码

private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {  

//check before file name is nt null
    File ModFile =new File("somefile" + ".mod");
    FileOutputStream writer = null;

    String toProcess = "00D0C0DE00D0C0DE F000000000000000";

    try {
        writer = new FileOutputStream(ModFile);
        writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);

    } catch (IOException ex) {
        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
    }finally{
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
于 2012-12-12T09:05:47.323 回答