2013-09-24 89 views
-3

我正在試圖製作一個讀取外部.txt文件並對其進行操作的程序。該文件有5個不同的數據組,每行4行(2個是int,2個字符串)。我需要使用Scanner類讀取文件,創建一個對象來保存每組數據(編寫一個將數據組存儲爲單個對象的類(讓我們稱之爲ProgramData))。然後,我需要創建一個ProgamData對象,並將其放入一個ArrayList中,併爲這5個組中的每一個重複。在Java中操作文本文件?

我有一個文本文件,我用掃描儀讀取它(我確認我是通過在命令行上打印完成的)。我完全失去了。任何幫助都將不勝感激。

不喜歡這樣會有幫助,但這裏是我到目前爲止的代碼:

import java.io.*; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class Project1 
{ 
    public static void main (String[] args) throws IOException 
    { 

     File dataFile = new File("C:\\Users/data.txt"); 
     Scanner fileReader = new Scanner(dataFile); 

     int firstLine = fileReader.nextInt(); 
     int secondLine = fileReader.nextInt(); 
     String whiteSpace = fileReader.nextLine(); 
     String thirdLine = fileReader.nextLine(); 
     String fourthLine = fileReader.nextLine(); 

     ArrayList<String> newArray = new ArrayList<String>(); 

    } 


} 
+2

你必須定義一個'ProgramData'類,併爲文件中的每組數據創建它的實例。 'ArrayList'應該是'ArrayList '。我們不會爲您編寫代碼,但這應該指向正確的方向。 –

+0

您需要標記您的字符串(現在代表您的文本文件)。根據可預測的東西標記它,如逗號(如果它是CSV),標籤(如果它是文本標籤分隔文件等)。或者如果所有東西都在它自己的行上,則用新的行字符標記(\ r \ n) \ n on * nix's) – SnakeDoc

+1

因此,您已經完成了簡單的工作......您需要對問題有一個最基本的瞭解,並尋求具體幫助方面的幫助,以便我們爲您提供幫助。 – Grammin

回答

0

確保當你正在閱讀的輸入文件,使用掃描儀類的hasNext()方法。它檢測文件中是否還有一行,因此您沒有到達文件末尾。使用它,像這樣

// get file input 
// this will make sure there are still lines left within the 
// file and that you have not reached the end of the file 
while(fileReader.hasNext()) { 

    int firstLine = fileReader.nextInt(); 
    int secondLine = fileReader.nextInt(); 
    String whiteSpace = fileReader.nextLine(); 
    String thirdLine = fileReader.nextLine(); 
    String fourthLine = fileReader.nextLine(); 

} 

你需要採取上述提供給你正在尋找的操作。

0

下面是步驟,你可以遵循:

  1. 創建一個名爲ProgramData
  2. 類做一個構造函數將接受您的組數據。 - > What is constructor
  3. 現在在Project1類中正確讀取文件。 - >Scanner TutorialReading a txt file using scanner java

  4. 一旦你得到所有從文件中的第一組數據把它傳遞給ProgramData類和創建實例類似

    ProgramData pd1 = new ProgramData (/* list of parameter */) 
    
  5. 添加一個ProgramData instace到ArrayList中像下面

    // Define Arraylilst 
    ArrayList<ProgramData > list= new ArrayList<ProgramData >(); 
    
    // Do some operation like reading or collecting the data and creating object 
    // shown in step 4 
    
    list.add(pd1); // add new object of group to list. 
    

我希望這將有助於ÿ ou實現你的目標。如果你有任何問題只是問。祝你好運