2014-02-22 62 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有一個有效的觀點。這是一個真正的應用以明文密碼存儲在一個文件不好的做法。但我懷疑這是一個練習......而文件格式已被指定爲其中的一部分。