2013-09-24 88 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实现你的目标。如果你有任何问题只是问。祝你好运