2015-11-19 67 views
1

我需要幫助構建一個數組,其中包含.txt文件的值。將文件中的單詞存儲到字符串中Java

文本文件(例如):

this is the text file. 

我想數組看起來像:

Array[0]:This 
Array[1]:is 
etc.. 

希望有人可以給我一隻手,我是familar着如何打開,創建並從文本文件中讀取,但目前就是這樣。我不知道如何閱讀數據後如何使用/播放數據。這是我迄今爲止建造的。

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

public class file { 

private Scanner x; 

    public void openFile(){ 
     try{ 
     x=new Scanner(new File("note3.txt")); 
     } 
     catch(Exception e){ 
     System.out.println("Could not find file"); }} 



    public void readFile(){ 
     String str; 

     while(x.hasNext()){ 
     String a=x.next(); 

     System.out.println(a);}} 

    public void closeFile(){ 
     x.close();}} 

單獨的文件中讀取...

public class Prac33 { 


    public static void main(String[] args) { 

    file r =new file(); 
     r.openFile(); 
     r.readFile(); 
     r.closeFile(); 
     } 
    } 

我希望這些存儲到一個數組,我可以在以後使用的文件按字母順序排序。

+1

使用數組的問題是你必須知道有多少話是在文本文件中的第一。列表可能會更好。 – Gary

+0

通過對文件進行排序,你的意思是用文字或句子來表達嗎? – gonzo

+0

通過單詞,我的目標是按字母順序對文件中的所有單詞進行排序,並刪除nessasry中的任何重複單詞。如果您希望以不同的角度接近問題,請告訴我。謝謝! –

回答

2

你可以先保存整個文件轉換成字符串,然後把它分解:

... 
    String whole = ""; 
    while (x.hasNext()) { 
     String a = x.next(); 
     whole = whole + " " + a; 
    } 
    String[] array = whole.split(" "); 
    ... 

或者你可以使用一個ArrayList,這是一種「清潔」的解決方案:

... 
    ArrayList<String> words= new ArrayList<>(); 
    while (x.hasNext()) { 
     String a = x.next(); 
     words.add(a); 
    } 
    //get an item from the arraylist like this: 
    String val=words.get(index); 
    ... 
+0

感謝您的快速回復,我感謝您的時間。我嘗試插入 –

+0

public void readFile(){ ArrayList words = new ArrayList <>(); while(x.hasNext()){ String a = x.next(); words.add(a); } –

+0

但我得到一個錯誤「<> operater不允許1.7以下的源代碼級別」? –

0

你可以添加到ArrayList而不是您的System.out.println(a);

然後,你可以當你使用完成轉換ArrayListString array

String[] array = list.toArray(new String[list.size()]); 
-3

使用

new BufferedReader (new FileReader ("file name")); 

隨着bufferedReader迭代的對象,並從文件中讀取行。發佈使用StringTokenizer來標記空格並將它們存儲到您的array

+1

'StringTokenizer'已被棄用多年。 'Scanner'是正確的類。 –

-1

這裏是你可以做什麼:

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

public class file { 

private Scanner x; 

public void openFile() { 
    try { 
     x = new Scanner(new File("note3.txt")); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public String[] readFile(String[] array) { 
    long count = 0; 
    while (x.hasNext()) { 
     String a = x.next(); 
     array[(int) count] = a; 
     System.out.println(a); 
     count++; 
    } 
    return array; 
} 

public void closeFile() { 
    x.close(); 
    } 
} 
相關問題