2015-08-15 65 views
0

所以我正在研究这个项目,帮助为我建立一个网站,我正在从一个文件夹(有文件)中读取数据并写入一个html文件。我做了一些小小的研究,但最终总是没有任何印刷或错误。让我知道是否有办法做到这一点?这是我的项目,我已经改变了文件夹的位置,并输出为.txt如何将文件夹中的信息传输到文件?

public class Project { 

@SuppressWarnings("resource") 
public static void main(String[] args) throws IOException { 

    PrintWriter out = new PrintWriter("output.txt"); 

    Files.walk(Paths.get("C:/Location")).forEach(filePath -> { 
     if (Files.isRegularFile(filePath)) { 

      out.print(filePath); 

      }  
     }); 
    } 
} 
+0

您是否尝试过打印控制台胀?有什么东西出现吗? –

+0

是的,当我打印控制台时,一切都显示出来。 – Joe

+0

你想用File.isRegularFile(Path p)完成什么?你在寻找一个不是目录的文件吗? – lacraig2

回答

1

@JoetheDailyProgrammer,你可能写错了文件。试试这个代码:

public static void main(String[] args) throws IOException { 

    File out = new File("output.txt"); 

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

运行它,它会显示你的绝对路径"output.txt"。如果指向到不同的位置,比你预期的,那么使用绝对路径在你的应用程序或使用用户主目录,如下所示:

public static void main(String[] args) throws IOException { 

    File outFile = new File(System.getProperty("user.home") + "/Desktop/output.txt"); // file into users homedir 

    System.out.println(outFile.getAbsolutePath()); // print it's location in console 

    PrintWriter out = new PrintWriter(outFile); // writer over that file 

    Files.walk(Paths.get("C:/Location")).forEach(filePath -> { 
     if (Files.isRegularFile(filePath)) { 

      out.print(filePath); 

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

UPD。

如果是真的你打算保存文件到桌面文件夹,那么很可能你应该浏览它就像在以下答案:

https://stackoverflow.com/a/1080900/2109067

https://stackoverflow.com/a/570536/2109067

所以:

public static void main(String[] args) throws IOException { 
    FileSystemView fsv = FileSystemView.getFileSystemView(); 
    File outFile = new File(fsv.getHomeDirectory() + "/output.txt"); // file into desktop dir 

    System.out.println(outFile.getAbsolutePath()); // print it's location in console 
    ... 
} 
1

确保使用的PrintWriter(“output.txt的”,真正的),以自动刷新,或者在程序结束冲洗。

public static void main(String[] args) { 
    PrintWriter out = new PrintWriter(System.out, true); 
    File dir = new File("images"); 
    String[] list = dir.list(); 
    if (list != null) { 
    for (String f : list) { 
     String[] fileName = f.split("\\."); 
     if (fileName.length > 1 && fileName[1].equals("png")) { 
     // System.out.println(f); 
     out.println(f); 
     } 

    } 
    } else { 
    System.out.println("list returned null because dir.canRead is " + dir.canRead()); 
    } 
} 

我改写了它在File类中的位。让我知道这是否需要改变。希望这可以帮助。

+0

我在这里遇到这个问题Exception in thread“main”java.lang.NullPointerException \t at Project.main(Project.java:14) – Joe

+0

尝试运行Files.canRead(您的文件)以查看您是否可以访问它。 – lacraig2

+0

@JoetheDailyProgrammer现在就试试。 – lacraig2

相关问题