2014-02-22 59 views
-2

我有一个文本文件,它看起来像这样的Java读取文件和分割线成阵列输出

respondentid |    name    |  email  | password | michid 
-------------+--------------------------------+---------------------+----------+-------- 
bi1004  | Malapa   Bushra   | [email protected] | ec59260f |  
bm1252  | Peter Benjamin T    | [email protected] | 266bff7c |  
dg1988  | Goday Priya     | [email protected] | dongara |  

我只需要打印出来只有电子邮件,姓名等..但名称是相反的顺序,包括中间初始..我如何处理逆序和中间初始?例如我的打印输出将是

[email protected] Bushra Malapa 
[email protected] Benjamin T Peter 

即时思考虐待使用拆分功能,也读入数组。你觉得怎么样?任何人都有这方面的经验?谢谢。

+3

_“即时通讯思想生病使用分割功能......” _做到这一点,如果你有任何问题,那么你可能会问这里 – Baby

+2

我认为最简单的方法是阅读在一时间整个行,然后把它分解通过'|'将字段和空格分开。 –

+0

从你给我们的代码量有限来看,似乎你存储在一个文件中,这是一个坏主意确实密码。 – GreySwordz

回答

2

这里是我会做什么:我会跳到第三行,然后使用分割功能分割线在每个“|”并将第二个和第三个值存储为名称和电子邮件。然后我们采用这个名称,每当有空间时就拆分它,并根据有多少部分重新排列它,无论是First First Last还是First Last。然后我们将它与电子邮件并排打印。

Soooooooo这里是什么样子:

import java.io.*; 
public class temp { 
    public static void main(String[] args) { 
     // define the path to your text file 
     String myFilePath = "temp.txt"; 

     // read and parse the file 
     try { 
      BufferedReader br = new BufferedReader(new FileReader(new File(myFilePath))); 
      String line, name, email; 
      // read through the first two lines to get to the data 
      line = br.readLine(); 
      line = br.readLine(); 
      while ((line = br.readLine()) != null) { 
       if (line.contains("|")) { 
        // do line by line parsing here 
        line = line.trim(); 
        // split the line 
        String[] parts = line.split("[|]"); 
        // parse out the name and email 
        name = parts[1].trim(); 
        email = parts[2].trim(); 
        // rearrange the name 
        String[] nParts = name.split(" *"); 
        if (nParts.length == 3) { 
         name = nParts[1] + " " + nParts[2] + " " + nParts[0]; 
        } else { 
         name = nParts[1] + " " + nParts[0]; 
        } 
        // all done now, let's print the name and email 
        System.out.println(email + " " + name); 
       } 
      } 
      br.close(); 
     } catch (Exception e) { 
      System.out.println("There was an issue parsing the file."); 
     } 
    } 
} 

如果我们继续前进,与你在这里提供的示例文件运行这个就是我们得到的:

[email protected]布沙拉马拉帕
[email protected]本杰明牛逼彼得
[email protected]普里亚Goday

希望这对你有帮助!我绝对鼓励你找到你自己的方式做到这一点也是如此,因为有很多不同的方式来解决问题,这是很好的找到一种方法,让你的感觉。还有人指出,你绝对不应该用纯文本存储密码。

1

因为你所要求的意见...

即时通讯思想生病利用分割功能,也读入数组。你觉得怎么样?

使用split函数将行分隔为字段是一种可能性。另一个是使用扫描仪。分割功能也可以用来将名字分成几部分。

读的东西成阵列是一个坏主意,因为你需要知道数组需要有多大是事先...并且一般来说有没有知道的方式。改为使用List


@GreySwordz有一个有效的观点。这是一个真正的应用以明文密码存储在一个文件不好的做法。但我怀疑这是一个练习......而文件格式已被指定为其中的一部分。