1

I have a text file like this :

abc def jhi
klm nop qrs
tuv wxy zzz

I want to have a string array like :

String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}

I've tried :

try
    {
        FileInputStream fstream_school = new FileInputStream("text1.txt");
        DataInputStream data_input = new DataInputStream(fstream_school);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
        String str_line;
        while ((str_line = buffer.readLine()) != null)
        {
            str_line = str_line.trim();
            if ((str_line.length()!=0)) 
            {
                String[] itemsSchool = str_line.split("\t");
            }
        }
    }
catch (Exception e)  
    {
     // Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

Anyone help me please.... All answer would be appreciated...

2
  • 2
    What have you tried? Commented Oct 12, 2012 at 10:39
  • Hello Edward, welcome to SO. Please choose a valid answer if your question has been answered, thanks :) Commented Oct 14, 2012 at 13:54

7 Answers 7

11

If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:

List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 I didn't knew the readAllLines utility which may be convenient for small files.
@assylias : I try this, But it show red underline on charset. What should I do ?
Provide the charset used by your file - typically, something like Charset.forName("UTF-8")
2

Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.

1 Comment

Note that he wants each line to be an entry in the array, not broken up by tokens within the line.
2

This is my code to generate random emails creating an array from a text file.

import java.io.*;

public class Generator {
    public static void main(String[]args){

        try {

            long start = System.currentTimeMillis();
            String[] firstNames = new String[4945];
            String[] lastNames = new String[88799];
            String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
            String firstName;
            String lastName;
            int counter0 = 0;
            int counter1 = 0;
            int generate = 1000000;//number of emails to generate

            BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
            BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
            PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));


            while ((firstName = firstReader.readLine()) != null) {
                firstName = firstName.toLowerCase();
                firstNames[counter0] = firstName;
                counter0++;
            }
            while((lastName= lastReader.readLine()) !=null){
                lastName = lastName.toLowerCase();
                lastNames[counter1]=lastName;
                counter1++;
            }

            for(int i=0;i<generate;i++) {
                write.println(firstNames[(int)(Math.random()*4945)]
                        +'.'+lastNames[(int)(Math.random()*88799)]+'@'+emailProvider[(int)(Math.random()*emailProvider.length)]);
            }
            write.close();
            long end = System.currentTimeMillis();

            long time = end-start;

            System.out.println("it took "+time+"ms to generate "+generate+" unique emails");

        }
        catch(IOException ex){
            System.out.println("Wrong input");
        }
    }
}

Comments

1

Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output).

Something like this:

    String[] arr= null;
    List<String> itemsSchool = new ArrayList<String>();

    try 
    { 
        FileInputStream fstream_school = new FileInputStream("text1.txt"); 
        DataInputStream data_input = new DataInputStream(fstream_school); 
        BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); 
        String str_line; 

        while ((str_line = buffer.readLine()) != null) 
        { 
            str_line = str_line.trim(); 
            if ((str_line.length()!=0))  
            { 
                itemsSchool.add(str_line);
            } 
        }

        arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
    }

Then the output (arr) would be:

{"abc def jhi","klm nop qrs","tuv wxy zzz"} 

This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.

5 Comments

Thanks, I think it's work but in the LogCat, show that : Error : /text1.txt: open failed: ENOENT ( No such file or directory)
You should have your text1.txt input file in your current directory (as you have it in your question) otherwise you need to provide the path along with the filename
yeah, I put it in the same folder. Sorry, I forgot mention that i'm developing android app. Will it be the same path as normal Java App ?
Yes in the same folder, but it's a good practice not to mess your configuration files with your source code. You'd better create a folder and place it there
I still found error. some tutorial mention about method getFileDir() of android in order to go the path of a file. when I use it, in LogCat ask me to put the file in /data/data/<package-name?/files/text1.txt. Can I change it to other folder ?
0

You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be..

 File file = new File("data.txt");

        try {
            //
            // Create a new Scanner object which will read the data 
            // from the file passed in. To check if there are more 
            // line to read from it we check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all line is read.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                //store this line to string [] here
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

Comments

0
    Scanner scanner = new Scanner(InputStream);//Get File Input stream here
    StringBuilder builder = new StringBuilder();
    while (scanner.hasNextLine()) {
        builder.append(scanner.nextLine());
        builder.append(" ");//Additional empty space needs to be added
    }
    String strings[] = builder.toString().split(" ");
    System.out.println(Arrays.toString(strings));

Output :

   [abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]

You can read more about scanner here

Comments

0

You can use the readLine function to read the lines in a file and add it to the array.

Example :

  File file = new File("abc.txt");
  FileInputStream fin = new FileInputStream(file);
  BufferedReader reader = new BufferedReader(fin);

  List<String> list = new ArrayList<String>();
  while((String str = reader.readLine())!=null){
     list.add(str);
  }

  //convert the list to String array
  String[] strArr = Arrays.toArray(list);

The above array contains your required output.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.