在Java中操作文本文件?
我试图制作一个程序,读入一个外部的.txt文件并对其进行操作。该文件有5组不同的数据,每组4行(2行为int,2行为string)。我需要使用Scanner类读取文件,创建一个对象来保存每组数据(编写一个类,将数据组存储为单个对象(我们称之为ProgramData))。然后我需要创建一个ProgamData对象并将其放入ArrayList中,然后对5个组中的每一个重复该操作 我有一个文本文件,我用扫描器读取它(我通过在命令行上打印确认我正确地做到了这一点)。我完全迷路了。任何帮助都将不胜感激 这样做没有帮助,但我的代码如下:在Java中操作文本文件?,java,text,arraylist,Java,Text,Arraylist,我试图制作一个程序,读入一个外部的.txt文件并对其进行操作。该文件有5组不同的数据,每组4行(2行为int,2行为string)。我需要使用Scanner类读取文件,创建一个对象来保存每组数据(编写一个类,将数据组存储为单个对象(我们称之为ProgramData))。然后我需要创建一个ProgamData对象并将其放入ArrayList中,然后对5个组中的每一个重复该操作 我有一个文本文件,我用扫描器读取它(我通过在命令行上打印确认我正确地做到了这一点)。我完全迷路了。任何帮助都将不胜感激 这
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>();
}
}
import java.io.*;
导入java.util.ArrayList;
导入java.util.Scanner;
公共类项目1
{
公共静态void main(字符串[]args)引发IOException
{
File dataFile=新文件(“C:\\Users/data.txt”);
Scanner fileReader=新扫描仪(数据文件);
int firstLine=fileReader.nextInt();
int secondLine=fileReader.nextInt();
字符串空白=fileReader.nextLine();
String thirdLine=fileReader.nextLine();
String fourthLine=fileReader.nextLine();
ArrayList newArray=新ArrayList();
}
}
确保在读取输入文件时,使用Scanner类的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();
}
您需要使用上面提供的来执行您正在寻找的操作 以下是您可以遵循的步骤:
ProgramData pd1 = new ProgramData (/* list of parameter */)
// 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.
//定义arraylist
ArrayList=新建ArrayList();
//执行一些操作,如读取或收集数据并创建对象
//如步骤4所示
列表。添加(pd1);//将组的新对象添加到列表中。
我希望这将帮助你实现你的目标。如果你有任何问题,尽管问。祝您好运您必须定义一个类
ProgramData
,并为文件中的每一组数据创建它的实例。ArrayList
应该是ArrayList
。我们不打算为您编写代码,但这将为您指明正确的方向。您将需要标记您的字符串(现在表示您的文本文件)。基于可预测的内容标记它,例如逗号(如果它是CSV),制表符(如果它是文本制表符分隔的文件)等。或者如果所有内容都在它自己的行上,则使用新行字符标记(\r\n在windows上,和\n在*nix上),这样您就完成了简单的部分。。。您需要对问题有一个最低限度的了解,并寻求具体帮助,以便我们帮助您。