0

你好我是java的新手。我上周刚开始学习java。

下面是我用来显示文件夹及其子文件夹的所有文件和相应文件大小的代码。

但是,我需要实现的实际上是将相同的数据输出到文本文件,而不是在 Eclipse 控制台中显示输出。在过去的几天里,我一直在网上搜索如何实现这一点,但我无法找到解决方案。

有人可以建议我使用什么代码来完成我的任务吗?

非常感谢!

public class ReadFile1 {
public static void main(String[] a)throws IOException{
showDir(1, new File("/Users/User/Documents/1 eclipse test/testfolder1"));

//File file = new File("/Users/User/Documents/1 eclipse test/testfolder1/puppy4.txt");

//long fileSize = file.length();

}
static void showDir(int indent, File file) throws IOException {


 for (int i = 0; i < indent; i++)

      System.out.print('-');
System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");


  if (file.isDirectory()) {
  File[] files = file.listFiles();
  for (int i = 0; i < files.length; i++)
    showDir(indent + 4, files[i]);  


   }

}

}
4

3 回答 3

1

这是您转换的示例:

public class ReadFile1
{
    public static void main(String[] a) throws IOException
    {
        FileWriter fstream = new FileWriter("C:\\test.txt",true);
        BufferedWriter out = new BufferedWriter(fstream);

        showDir(out,1,new File("C:\\"));

        out.flush();
        out.close();
    }

    static void showDir(BufferedWriter writer, int indent, File file) throws IOException
    {
        for(int i = 0; i < indent; i++)
        {
            writer.write('-');
            //System.out.print('-');
        }

        writer.write(file.getName() + " - " + file.length() / 1024 + " KB");
        writer.newLine();

        //System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");

        if(file.isDirectory())
        {
            File[] files = file.listFiles();
            for(int i = 0; i < files.length; i++)
            {
                showDir(writer,indent + 4, files[i]);
            }
        }
    }
}
于 2013-05-22T07:17:45.383 回答
0

使用此处提到的文件编写代码更新您的 showDir:

File file = new File("info.txt");
 // if file doesnt exists, then create it
  if (!file.exists()) {
        file.createNewFile();
}

PrintWriter writer = new PrintWriter(file);
writer.println(file.getName() + " - " + file.length() / 1024 + " KB");
writer.close();
于 2013-05-22T07:14:21.117 回答
0

这会将控制台输出放入文本文件中:

   try{
    PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
    System.setOut(out);
    }catch(SecurityException se){
       //Exception handling
      }

setOut(PrintStream out)SecurityException重新分配“标准”输出流。如果安全管理器存在并且它的 checkPermission 方法不允许重新分配标准输出流,它会抛出。

于 2013-05-22T07:15:13.773 回答