繁体   English   中英

(Java)读取文件,将字符串信息存储到数组中,并将此字符串的变体写出

[英](Java) Reading in a file, storing string information into an array, and writing a variation of this string out

这个问题使我工作了几个小时,因此,我将不胜感激。 我需要通过命令行参数读取一个文件,该文件包含多个学生的姓名,专业,ID和毕业日期。 然后,我需要将此信息存储在一个数组中,并使用该数组仅输出满足条件的特定学生的信息(他们将于2017年毕业)。 因此,基本上我正在输出一个仅包含符合此条件的学生的新文件。

我创建了此代码以读取文件并将其存储到数组中。 但从这里,我很沮丧:(

请,任何帮助将是宝贵的。

import java.util.*;
import java.io.*;
import java.io.File;

public class Aid {

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


        String token1 = "";

        Scanner inFile1 = new Scanner(new File("location of file in my folder")).useDelimiter(",\\s*");


        List<String> temps = new ArrayList<String>();

        while (inFile1.hasNext()) {
           token1 = inFile1.next();
           temps.add(token1);
        }
        inFile1.close();

        String[] tempsArray = temps.toArray(new String[0]);

        for (String s : tempsArray) {
            System.out.println(s);
        }
    }
}

您是否需要以这种形式回答? 您应该使用split而不是stringtokenzier。 为了简单起见,从文件中读取数据,

创建一个String类型的arrayList,以便您可以根据需要调整大小。

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

创建一个File对象。 File thisFile = new File( 要读取的文件名去

创建您的扫描仪。 Scanner scanThis = new Scanner(thisFile);

while(scanThis.hasNext())
{
String str = scanThis.next();
info.add(str);
}

我已经编程了2个星期左右,如果我错了病,请随时纠正我自己;)

添加另一个答案,因为可能很难从评论中阅读

import java.io.*;
import java.util.*;
/**
 * Write a description of class Other here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Other 
{
public static void main(String[] args) throws IOException
{
File myFile = new File("Users/josephcrachiolo/Desktop/ReadThis.txt"); //Create a file object and hold the name of our file.
Scanner readThis = new Scanner(myFile); //Scanner object to read from the file
ArrayList<String> temp = new ArrayList<String>(); arraylist for the purpose of resizing array
StringTokenizer stok; //Not needed i believe
PrintWriter output = new PrintWriter("Yalla.txt"); //create a printwriter object so we can write to the specified file "Yalla.txt"
int i = 0; //Used as incrementor

while(readThis.hasNext()) //while the file has something to be read
{
String str = readThis.next(); //Here will read each peice of text and will seperate by spaces
//stok = new StringTokenizer(str) --> possibly not needed
temp.add(str); //add to the arraylist object //add that text into our arraylist
}
while(!temp.isEmpty()) //while our arraylist is not empty execute
{
output.print(temp.get(i)); //print to the output object("Yalla.txt") the first element (0)
i++; //increase the element to get the next.
}

所有这些都应从文件中读取,并将其存储在另一个文件中。 由于路径错误而无法编译,因此获得了新的Mac IDK,但工作原理却是,请让我知道是否出现问题readThis.close(); output.close(); }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM