我正在编写一个应用程序,该应用程序搜索给定目录及其子目录中的Java文件,并将所有字符串从这些文件反向写入一个新文件夹。每个目录和文件都在一个单独的线程中处理。目前,我的程序工作正常,但我想改变它的行为。现在,程序正确地覆盖文件,并将覆盖文件的数量输出到控制台的末尾。我希望我的程序只是覆盖文件,并显示行“所有文件覆盖”在末尾。但我不太明白如何更改代码并替换未来(我认为这是我的问题)。下面是主类代码的一部分:
ExecutorService pool = Executors.newCachedThreadPool();
ReverseWritter reverseWritter = new ReverseWritter(dirToSearch, dirToStorePath + "//" + dirToStoreName, pool);
Future<Integer> res = pool.submit(reverseWritter);
try {
System.out.println(res.get() + " files reversed");
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();下面是覆盖文件的方法:
public boolean reverseWrite(File file) {
if (file.isFile() && file.toString().endsWith(".java")) {
String whereTo = dirToStorePathName + "\\" + file.getName().substring(0, file.getName().indexOf(".java")) + "Reversed" + ".java";
try ( Scanner myReader = new Scanner(file); FileWriter myWriter = new FileWriter(whereTo);) {
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
myWriter.write(new StringBuffer(data).reverse().toString());
myWriter.write(System.getProperty("line.separator"));
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
return false;
}
}
return true;
}这是call方法(我的类实现了可调用接口):
@Override
public Integer call() {
int count = 0;
try {
File[] files = dirToSearch.listFiles();
ArrayList<Future<Integer>> result = new ArrayList<>();
for (File f : files) {
if (f.isDirectory()) {
ReverseWritter reverseWritter = new ReverseWritter(f, dirToStorePathName, pool);
Future<Integer> rez = pool.submit(reverseWritter);
result.add(rez);
} else if (reverseWrite(f)) {
count++;
}
for (Future<Integer> rez : result) {
count += rez.get();
}
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return count;
}发布于 2022-09-24 15:29:08
您只需更改类以实现Callable<Void>,并删除执行计数的操作。将call的返回类型从Integer更改为Void。
public class ReverseWriterCallable implements Callable<Void> {
@Override
public Void call() throws Exception {
//do stuff
//don't do the counting operations
//when return type is Void you can only return null
return null;
}
}或者实现Runnable并将其提交给executor服务。
public class ReverseWriterRunnable implements Runnable {
@Override
public void run() {
//do stuff
//don't do the counting operations
}
}那就别在意Future的结果了
try {
res.get();
System.out.println("All files reversed");
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();https://stackoverflow.com/questions/73837729
复制相似问题