繁体   English   中英

我想将多个字符串从Java中的.txt文件解析为变量。 最简单的方法是什么?

[英]I want to parse multiple strings into variables from a .txt file in java. What's the easiest way to do it?

最好的方法是什么? 我应该使用File类和扫描仪吗? 我以前从未做过,而且似乎也找不到在线的可靠指南,因此我想在这里问一下。

编辑:
我正在解析的文本文件是3列,前三列是ID NAME BIRTHDATE,然后是实际数据。

编辑(来自pastie的代码):

public void readFromFile(File file ) 
{
    try
    {
        System.out.println("success..");
        s = new Scanner(file);
        BufferedReader input = new BufferedReader(new FileReader(file));
        String jj = null;
        while((jj = input.readLine())!=null)
        {  
            String [] words = jj.split("\\t");
            String name = "";
            String id = "";
            String birthdate ="";
            for (int i = 3; i<words.length; i+=3)
            {
                id =words[i];
                name = words[i+1];
                birthdate=words[i+2];
                Person p = new Person(id, name, birthdate);
                peopleMap.put(p.id,p);
                names.add(p);
                System.out.println("New entry added to file: "+name+"\\t"+"ID: "
                                    +id+"\\t"+"Birthdate"+birthdate);
            }
        }
    }

    catch(IOException e)
    {
    }
}

最简单的方法取决于文本文件的格式。 从您的其他评论看来,这些行是制表符分隔的值。 作为初学者,您可能会发现使用Scanner最简单。 具体来说,就是Scanner.nextLine()。 结合使用String.split(“ \\ t”)将数据拆分为一个数组(假设格式为制表符分隔值)。

仅仅取决于文本文件的格式。

  1. 如果是简单名称/值对,则可以使用java.util.Properties。 例如a.properties可能看起来像:

     name=john city=san jose date=12 july 2010 

那么您可以将其加载为:

Properties props = new Properties();
props.load(new FileInputStream("a.properties"));
  1. 如果format与java.util.Properties.load()支持的格式不同,则使用java.util.Scanner逐行处理将很有帮助:

     File file = new File("data.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); //Process each line seperately processLine(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } 

如果您可以随意声明文本文件的语法/结构是什么,那么可以考虑将其设为Java属性文件。 然后,您可以使用java.util.Properties类以最少的编程工作来加载和保存文件。

在这种情况下,我喜欢这样做:

Scanner s = new Scanner(file);
Scanner line;
String name;
String date;
int id;
while(s.hasNext()){
   line = new Scanner(s.nextLine());
   id = line.nextInt();
   name = line.next/*String*/();
   date = line.next/*String*/();
   /* Do something with id, name and date */
}

也许有一些异常处理或类似的东西

(有人想评论创建许多新扫描仪的效率吗?)

暂无
暂无

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

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