簡體   English   中英

如何獲得一種方法來讀取Java中的文件輸入?

[英]How to get a method to read a file input in Java?

如果我有以下代碼:

public Bicycle(int maxSpeed, String brand, int numOfGears, String name) {

我希望它讀取一個具有以下一行信息的.txt文件:“ 3,Huffy,6,Charles”,並返回一個包含該信息的對象-怎么做是最好的方法?

執行以下操作足以做到這一點嗎?

public Bicycle(int maxSpeed, String brand, int numOfGears, String name) {
    Bicycle newBike = new Bicycle (read information from file here);
}

請讓我知道是否可以進一步澄清這個問題。

這是讀取單行的近似代碼

File file = new File("test.txt");
FileReader reader = new FileReader(file);
BufferedReader buf = new BufferedReader(reader);
String line = buf.readLine();
String[] tokens = line.split(",");
int number = Integer.parseInt(tokens[0].trim());
String name = tokens[1].trim();

您將需要調整路徑文本文件,並處理可能出現的FileNotFoundException ,也IOException的buf.readLine() buf.readLine() 一旦有了字符串,就將其拆分。 您可以提取變量並使用它們。 確保文件中的數據匹配預期的模式-因此需要其他異常處理。 一旦獲得所有四個變量,就可以構造Bicycle

您可以使用commons.io

    String s = FileUtils.readFileToString(new File("{filePath}"));
    String[] words = s.trim().split(",");
    object1.setNumber(words[0]);
    object1.setName(words[1]);
    object2.setNumber(words[2]);
    object2.setName(words[3]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM