我正在尝试使我的代码更加模块化。我的问题是,一旦你通过调用getFile方法得到输入,你怎么能保存它来说一个数组等?
为了更清楚,我希望能够调用getFileScanner方法并返回用户输入的文件上的内容。然后在main方法中,我希望能够将该输入(无论是.txt文件中的任何内容)设置为数组(要写入)。如何在main方法中保存输入?在另一篇与此文章分开的帖子中,用户建议我使我的代码更加模块化并提出以下代码。我只是想了解用户的意图,并将一些代码分开。
import java.io.File ;
import java.io.FileNotFoundException ;
import java.util.Scanner ;
public class scanTest {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Please enter the file");
System.out.println(getFileScanner());
}
public static Scanner getFileScanner() throws FileNotFoundException {
Scanner user_input = new Scanner(System.in);
String filepath = user_input.next();
System.out.println("Filepath read: " + filepath);
// Read input file
Scanner input = new Scanner(new File(filepath));
System.out.println(input);
return input;
}
}
答案 0 :(得分:0)
使代码更加模块化意味着将代码分解为更小,自包含,可能可重用的部分。类似的东西:
public class ScanTest {
public static void main(String []args) throws FileNotFoundException {
Scanner user_input = new Scanner(System.in);
String filepath = getFilePath(user_input);
String[] all_lines = readAllLines(filepath );
}
public static String getFilePath(Scanner user_input) {
String filepath = user_input.next();
System.out.println("Filepath read: " + filepath);
return filepath;
}
public static String[] readAllLines(String filepath) throws FileNotFoundException {
// TODO: implement
}
}
这是一种更“模块化”的方法。每种方法都做了一个明确定义的事情。
但你的问题实际上是“如何将文件读入数组。”
public static String[] readAllLines(String filepath) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(filepath), StandardCharsets.UTF_8);
return lines.toArray(new String[list.size()]);
}