我正在尝试从日志报告创建一个文件。为了保存文件,我创建了一个按钮。当按钮被按下时,执行以下代码:
public void SAVE_REPORT(KmaxWidget widget){//save
try {
String content = report.getProperty("TEXT");
File file = new File("logKMAX.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} //SAVE_REPORT
我没有编译错误,但是没有保存任何文件。
有什么问题吗?
使用新的文件API。首先,在您的程序中,您不验证.createNewFile()
的返回值:它不会在失败时抛出异常…
使用新的文件API,它要简单得多:
public void saveReport(KmaxWidget widget)
throws IOException
{
final String content = report.getProperty("TEXT");
final Path path = Paths.get("logKMAX.txt");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.CREATE);
) {
writer.write(content);
writer.flush();
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class moveFolderAndFiles
{
public static void main(String[] args) throws Exception
{
File sourceFolder = new File("c:\Audio Bible");
copyFolder(sourceFolder);
}
private static void copyFolder(File sourceFolder) throws Exception
{
File files[] = sourceFolder.listFiles();
int i = 0;
for (File file: files){
if(file.isDirectory()){
File filter[] = new File(file.getAbsolutePath()).listFiles();
for (File getIndividuals: filter){
System.out.println(i++ +"t" +getIndividuals.getPath());
File des = new File("c:\audio\"+getIndividuals.getName());
Files.copy(getIndividuals.toPath(), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}