在下面的问题中,我必须读取文本文件并进行一些“处理”。教程中有很多读取文件的方法。但是,我想测试我的代码,甚至不先读取文件。相反,我想读取带有某个类的文件,该类具有实用程序方法来将行注入(inject)其中,而不是实际从文件中读取它们。哪种文件读取方法可以让我做到这一点?
我需要的伪代码:
TestableFileReader.injectLine("1.0, 2.0, 3.0, -1100");//Garbage data in line.
String line = TestableFileReader.readNextLine();
doProcessing(line);
Write a method public ArrayList readValues(String filename) throws ... that reads a file containing floating-point numbers. Throw appropriate exceptions if the file could not be opened or if some of the inputs are not floating-point numbers.
最佳答案
这是执行此操作的代码。可以重构代码,以便轻松地使用字符串行的各种值进行自动化测试,而不是硬编码固定字符串,如下所示。
//Method signature from book.
public static List<Double> readValues(String filename) throws IOException {
ArrayList<Double> values = new ArrayList<>();
String line = "1.0, 2.5, 3, -5, A, ë";
Reader reader = new StringReader(line); //new FileReader(filename);
//Is there a shorter way to do this, i.e without try-catch ?
Function<String, Boolean> isStringDouble = (string -> {
try{
return Double.valueOf(string) instanceof Double;
}catch (NumberFormatException ex){
return false;
}
});
//Decorate reader with BufferedReader to get readLine functionality.
try(BufferedReader bReader = new BufferedReader(reader)){
while ((line = bReader.readLine()) != null) {
Map<Boolean, List<String>> lineParts = Arrays
.stream(line.split(","))
.map(v -> v.trim())
.collect( Collectors.groupingBy(v -> isStringDouble.apply(v)) );
lineParts.forEach( ( (k, v) -> System.out.printf("are doubles = %s : %s\n", k, v) ) );
}
}
return values;
}
public static void main(String [] args) throws Exception {
readValues("hello");
}
关于java - 读取文件 - 哪种方法是可测试的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610678/