需要帮助修改代码:Java FileIO

时间:2015-10-06 09:24:29

标签: java string file-io bufferedreader filereader

我需要帮助修改代码。鉴于在记事本上,写的是名字中间名和姓。创建的代码如下:

http://www.mega.pk/**washingmachine**-dawlance/
http://www.mega.pk/**washingmachine**-haier/
http://www.mega.pk/**airconditioners**-acson/
http://www.mega.pk/**airconditioners**-lg/
http://www.mega.pk/**airconditioners**-samsung/

我想显示名字中间和最后一个。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用String的split()方法。修改后的代码看起来像这样

    BufferedReader f = new BufferedReader(new FileReader("Names.txt"));
    String n = f.readLine();
    while (n != null)
    {
        String[] names = n.split("\\s");
        System.out.println("First Name: " + names[0]);
        System.out.println("M.I: " + names[1]);
        System.out.println("Family Name: " + names[2] + "\n");
        n = f.readLine();
    }

答案 1 :(得分:0)

我会用String.split()来做。如果您的文本文件如下所示:" Tom TW Wellbrock"我会在空白处分隔输入字符串。如果您的属性用逗号分隔,请将其拆分:

    BufferedReader fileReader = new BufferedReader(new FileReader("Names.txt"));
    String input = fileReader.readLine(); //please choose other names for you variables they are confusing

     while (input != null){

      String[] parts = input.split(" "); //you can seperate with any Symbol
      System.out.println(parts[0]) //your first name
      System.out.println(parts[1]) //your initial
      System.out.println(parts[2]) //your last name
      input = fileReader.readLine();
     }