简体   繁体   中英

Storing words from a file into a string Java

I need help constructing an array in which it would hold the values of .txt file.

Text file (example):

this is the text file.

I would want the array to look like:

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

Hoping someone can give me a hand, i am familar with how to open, create and read froma text file, but currently that is about it. I do not know how to use/play around with the data once i can read it. This is the could i have constructed so far.

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();}}

Seperate file which reads...

    public class Prac33 {


    public static void main(String[] args) { 

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

I am hoping to store these into an array which i can later use to sort the file alphabetically.

You could store the whole file into a string first, then split it:

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

Or you could use an ArrayList , which is a 'cleaner' solution:

    ...
    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);
    ...

You can add to an ArrayList instead of your System.out.println(a); .

Then, you can convert the ArrayList to a String array when you're done using:

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

Here is what you can do:

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();
    }
}

Use

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

With the object of bufferedReader iterate and read lines from the file. Post that use StringTokenizer to tokenise based on " " empty space and store them to your array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM