我有一个 ReadFromFile 类实现 Callable 并返回字符串列表。这个字符串列表应该显示在控制台中,但奇怪的是它没有显示。在调试器中,我看到列表不为空,并且里面的数据是正确的。但不显示。
这是代码:
从文件读取
public class ReadFromFile implements Callable<List<String>> {
private File file;
public ReadFromFile(File file) {
this.file = file;
}
@Override
public List<String> call() throws Exception {
String row = null;
List<String> data = new ArrayList<>();
try (BufferedReader csvReader = new BufferedReader(new FileReader(file))) {
while ((row = csvReader.readLine()) != null) {
data = Arrays.asList(row.split(";"));
}
} catch (IOException i) {
System.out.println("Break");
}
return data;
}}
以下是方法,应将 future 的数据分配给要显示的列表:
public static void setupShop(List<String> menuItems, Map<String, Integer> stock, Map<String, Float> price) throws IOException, ExecutionException, InterruptedException {
menuItems = Executors.newFixedThreadPool(1).submit(new ReadFromFile(menuFile)).get();
}
我在这里排除了 map 代码,它不会影响这种情况。
但是!如果我创建另一个列表并将 Future 中的数据分配给它,数据将正确显示:
public static void setupShop(List<String> menuItems, Map<String, Integer> stock, Map<String, Float> price) throws IOException, ExecutionException, InterruptedException {
List <String> menu = new ArrayList<>();
menu = Executors.newFixedThreadPool(1).submit(new ReadFromFile(menuFile)).get();
for (int i = 0; i<menu.size();i++)
{
menuItems.add(menu.get(i));
}
那么,问题是,为什么我不能直接打印 future.get 中的数据?
最佳答案
data = Arrays.asList(row.split(";"));
这行是错误的,您重新分配列表,以便列表将采用文件最后一行的值。
使用 data.addAll(Arrays.asList(row.split(";")));
代替。也许问题就在这里,假设你的最后一行是空行
更新:
这是一个可重现的最小工作示例:
public class ReadFromFile implements Callable<List<String>> {
private File file;
public ReadFromFile(File file) {
this.file = file;
}
@Override
public List<String> call() throws Exception {
String row = null;
List<String> data = new ArrayList<>();
try (BufferedReader csvReader = new BufferedReader(new FileReader(file))) {
while ((row = csvReader.readLine()) != null) {
data.addAll(Arrays.asList(row.split(";")));
}
} catch (IOException i) {
System.out.println(i.getMessage());
}
return data;
}
}
使用主类进行测试
public class Main {
public static void main(String[] args) {
try {
List<String> menu = Executors.newFixedThreadPool(1).submit(new ReadFromFile(new File("src/test.csv"))).get();
menu.forEach(System.out::println);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
CSV 文件:
sfdfdsf;fdsgfdfsg;gfdgff
gfsgfd;fgfdg;gfgdfg
主执行的输出:
sfdfdsf
fdsgfdfsg
gfdgff
gfsgfd
fgfdg
gfgdfg
关于java - 无法从返回字符串列表的 Future 对象打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58950250/