【问题标题】:Where do i have to put input file in eclipse(java) in order to write into it我必须在哪里将输入文件放在 eclipse(java) 中才能写入它
【发布时间】:2014-10-06 11:12:43
【问题描述】:

我正在尝试从 java 程序将数据输入到文本文件中。该程序正在执行并将输出显示为成功,但是当我打开文本文件时它仍然是空白的。 这是我的代码

package com.example.ex2;


import java.io.*;  
class Input{  
  public static void main(String args[]){  
   try{  
     FileOutputStream fout=new FileOutputStream("abc.txt");  
     String s="Good MOrning";  

     byte b[]=s.getBytes();  
     fout.write(b);  

     fout.close();  

     System.out.println("success...");  
    }catch(Exception e){

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

我认为我在放置文本文件时出错了。我已经把它放在了默认目录下。

【问题讨论】:

  • 我在我的机器上测试了你的确切代码,它运行良好。运行程序后检查文件是否正确?
  • 你能告诉我你把文本文件放在哪里了吗?我想我在那里出错了
  • 它被默认放置在与Java项目相同的文件夹中。

标签: java eclipse io


【解决方案1】:

您的代码运行良好。检查正确的文件。

如果您从 IDE 运行,它将位于当前工作目录中。

最好使用临时或目录来存储文件(当然不在工作目录中)

这是一个最佳实践代码。如果您愿意,可以进一步调整它

public static void main(String args[])
    {
        FileOutputStream fout = null;
        try
        {
            File f = new File("abc.txt");
            if (!f.isFile())
                f.createNewFile();
            fout = new FileOutputStream(f);
            String s = "Good MOrning";

            byte b[] = s.getBytes();
            fout.write(b);

            System.out.println("success... printed at : " + f.getAbsolutePath());
        } catch (Exception e)
        {
            System.out.println(e);
        } finally
        {
            if (null != fout)
                try
                {
                    fout.close();
                } catch (IOException e)
                {
                }
        }
    }

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2013-10-30
    • 2016-07-23
    相关资源
    最近更新 更多