Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Read a list from a flat file and create an array in JAVA

Posted on 2011-05-02
8
Medium Priority
?
220 Views
Last Modified: 2012-05-11
I need to read a flat file (could be a .txt or properties file) and create an array. The flat file will have data separated by newline. Example the contents of the flat file could be

abc
cde
efg
ijg
lmn

After reading the above the array should have 5 elements containing the data.

0
Comment
Question by:PearlJamFanatic
8 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 35504139
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35504151
If you absolutely must have an array:
StringList sl = new StringList();
sl.read("YourFile.txt");
String[] data = sl.toArray(new String[sl.size()]);

Open in new window

0
 
LVL 20

Expert Comment

by:a_b
ID: 35504155
ArrayList<String> list = newArrayList<String> ();
Scanner in = new Scanner(<filepath>);
while(in.hasNext())
{
     list.add(in.nextLine());
}

//I've omitted the try catch block
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Assisted Solution

by:objects
objects earned 500 total points
ID: 35504157
0
 

Assisted Solution

by:katrixlabs
katrixlabs earned 500 total points
ID: 35504829
Just mention the complete path and send it as parameter to read() method.


public void read(String filepath){
            try{
                  DataInputStream dis = new DataInputStream(new FileInputStream(filepath));
                  StringBuffer buffer = new StringBuffer();
                  String content = "";
                  while((content = dis.readLine()) != null){
                        buffer.append(content);
                  }
                  String[] array = buffer.toString().split(",");                  
            }
            catch(Exception e){
           e.printStackTrace();
            }
      }
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 35506136


This is compiled and tested program which does it:


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;

public class ReadArray {
                          String [] myArray;
    public ReadArray() {


        ArrayList al = new ArrayList();
        try{
        DataInputStream in = new DataInputStream(new FileInputStream("myfile.properties"));
            String buff = null;
            while((buff=in.readLine())!=null){
                al.add(buff.trim());

            }
           in.close();


    }  catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }

         myArray = new String[al.size()];
        for(int jj=0; jj<al.size(); jj++){
            myArray[jj]=(String) al.get(jj);
        }


}

    public String []  getArray() {
      return myArray;

    }


    public static void main(String [] args){
        ReadArray ra = new ReadArray();
        String [] myArray = ra.getArray();
        for(int jj=0; jj<myArray.length; jj++){
            System.out.println(myArray[jj]);
        }


    }
}

Open in new window


This is the input form myfile.properties:

abc
cde
efg
ijg
lmn

Open in new window


This is the output:

abc
cde
efg
ijg
lmn

Open in new window


By the way if you really want to read properties file,
then there is a special method, something like that:

http://download.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.Reader%29

But this program can also be easily modified for straightforward properties files

0
 

Author Closing Comment

by:PearlJamFanatic
ID: 35510386
Sorry the scanner thing didn't work.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35510854
:)
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month11 days, 4 hours left to enroll

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question