Java 如何将输出保存到txt文件
快速Q 我有一个循环,可以找到目录中的所有文件,我想做的是在其中添加一行代码,将这些结果写入一个txt文件,我如何才能最好地做到这一点 当前代码:Java 如何将输出保存到txt文件,java,Java,快速Q 我有一个循环,可以找到目录中的所有文件,我想做的是在其中添加一行代码,将这些结果写入一个txt文件,我如何才能最好地做到这一点 当前代码: public String FilesInFolder() { // Will list all files in the directory, want to create a feature on the page that can display this to the user String path = N
public String FilesInFolder() {
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
return "";
}
与及:
你可以一起使用和
public String FilesInFolder() throws IOException {
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
sw.write(files);
System.out.println(files);
}
}
fw.write(sw.toString());
fw.close();
return "";
}
public String FilesInFolder() throws IOException {
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
sw.write(files);
System.out.println(files);
}
}
fw.write(sw.toString());
fw.close();
return "";
}