gpt4 book ai didi

java - 遍历目录,读入文件,并将它们打印到 html 文件中

转载 作者:行者123 更新时间:2023-12-02 07:42:17 24 4
gpt4 key购买 nike

我试图从 JfileChooser 选择一个目录,然后迭代该目录,读取所有文件并将它们全部写入一个大 HTML 文件中,以便于查看。以下是完成此操作的代码片段:

else if(arg0.getSource()==generate){
//Create HTML report in same directory that file(s) came from
try{

fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnval = fileChooser.showSaveDialog(this);
if(returnval == JFileChooser.APPROVE_OPTION){
File fileName = new File( "./report.html" );
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write("<html>");
bw.write("<body>");
bw.write("<h1>Graded Assignment</h1>");
bw.write("<p>");
//for loop here that appends all the files in a directory
File directory = new File(fileChooser.getSelectedFile().getAbsolutePath());
for( File f : directory.listFiles() ){
FileInputStream fstream = new FileInputStream(f);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
bw.write(br.readLine() + "\n");
}
bw.write("</p>");
bw.write("</body>");
bw.write("</html>");

bw.close();
Desktop.getDesktop().browse(fileName.toURI());
}
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch(IOException io){
io.printStackTrace();
}

它将进入 for 循环,但不会在第一个文件中读取。我收到某种 AWT-EventQueue 错误。谁能重现这个并告诉我问题可能是什么?谢谢。

最佳答案

如评论中所示,您应该检查它是否是目录并采取适当的措施:

File directory = new File(fileChooser.getSelectedFile().getAbsolutePath());
getFiles(directory);//calls method to get all the files in the directory
...
void getFiles(File directory) {
for( File f : directory.listFiles() ){
if(!f.isDirectory()) {//is a file lets read it
FileInputStream fstream = new FileInputStream(f);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
bw.write(br.readLine() + "\n");
}else {//wil make it a recursive search
getFiles(f);
}
}
}

尽管我给出的方法也进行递归文件搜索,如果给定目录中有一个目录,它将遍历其所有目录获取所有文件

附录:

您应该使用:chooser.showOpenDialog(),而不是chooser.showSaveDialog(),请参阅此处的示例:

   JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(parent);//this must be changed
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getAbsolutePath());
}

引用文献:

关于java - 遍历目录,读入文件,并将它们打印到 html 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com