Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列表和文件_Java_List_File Io - Fatal编程技术网

Java 列表和文件

Java 列表和文件,java,list,file-io,Java,List,File Io,如何使用JAVA在文件中编写列表 我正在写一个程序来搜索目录中的文件并显示它。我还有一个条件,我应该将搜索结果存储在日志文件中。所以请帮我做这个 从评论中: public void saveSearchResult(List<String> SearchResult) throws FileNotFoundException { File file1 = new File("D://result.log"); FileInputStream in = new File

如何使用JAVA在文件中编写列表

我正在写一个程序来搜索目录中的文件并显示它。我还有一个条件,我应该将搜索结果存储在日志文件中。所以请帮我做这个

从评论中:

public void saveSearchResult(List<String> SearchResult) throws FileNotFoundException {
    File file1 = new File("D://result.log");
    FileInputStream in = new FileInputStream("D://result.log");
    FileOutputStream out = new FileOutputStream(file1);
    DataInputStream din = new DataInputStream(in);
    DataOutputStream dout = new DataOutputStream(out);
    for (String search : getSearchResult()) {
        //Not getting hw to do this
    }
}
public void saveSearchResult(列出SearchResult)引发FileNotFoundException{
File file1=新文件(“D://result.log”);
FileInputStream in=newfileinputstream(“D://result.log”);
FileOutputStream out=新的FileOutputStream(file1);
DataInputStream din=新的DataInputStream(in);
DataOutputStream dout=新的DataOutputStream(输出);
for(字符串搜索:getSearchResult()){
//没有让hw这么做
}
}

将结果放入字符串中。然后将其加载到文件中,如下所示

StringBuilder s = new StringBuilder();
 for (String search : getSearchResult()) {
     s.append(search); //add formatting here as desired
    }

    try (FileWriter t = new FileWriter(new File("result.log"))) {
            t.write(s.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
您应该始终使用如上所述的try with resources语句,因为它将确保资源被释放

对于正在增长的字符串,您应该使用

您可能想要创建多个新的日志文件,在这种情况下,我建议用以下代码替换
“result.log”

新简化格式(“YYYY-MM-dd_hh-MM-ss”)。格式(新日期(
System.currentTimeMillis())+“.log”

这将输出您的日志文件,因此看起来像这样

结果_2014-02-13_5-19-44.log

年/月/日/时/分/秒


这听起来像是你可以很容易地用循环来做的事情。到目前为止,您尝试了什么?public void saveSearchResult(List SearchResult)抛出FileNotFoundException{File file1=new File(“D://result.log”);FileInputStream in=new FileInputStream(“D://result.log”);FileOutputStream out=new FileOutputStream(file1);DataInputStream din=new DataInputStream(in);DataOutputStream dout=new DataOutputStream(out);for(字符串搜索:getSearchResult()){//没有让hw执行我试图实现的上述代码。我正在学习文件流概念。请帮助我。您将希望将所有代码作为对原始问题的编辑发布。代码在注释中格式不好,无法阅读。如果您是新用户,这两页非常有用。和。