[英]Storing words from a file into a string Java
我需要構造一個數組來保存.txt文件的值。
文本文件(示例):
this is the text file.
我希望數組看起來像:
Array[0]:This
Array[1]:is
etc..
希望有人可以幫我忙,我熟悉如何打開,創建和讀取文本文件,但目前僅此而已。 一旦讀取數據,我不知道如何使用/處理數據。 這是我到目前為止構建的。
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();
}
}
我希望將這些存儲到一個數組中,以后可以用來按字母順序對文件進行排序。
您可以先將整個文件存儲為一個字符串,然后將其拆分:
...
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);
...
您可以添加到ArrayList
而不是System.out.println(a);
。
然后,可以使用以下命令將ArrayList
轉換為String array
:
String[] array = list.toArray(new String[list.size()]);
您可以執行以下操作:
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();
}
}
采用
new BufferedReader (new FileReader ("file name"));
使用bufferedReader
的對象迭代並讀取文件中的行。 郵政使用StringTokenizer
來tokenise基礎上" "
空的空間,並將其存儲到您的array
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.