Solved

random values stored in a .txt file

Posted on 2003-11-03
10
251 Views
Last Modified: 2010-03-31
hi all together,

I´m a completely newbie in java, but I think my question shouldn´t be too difficult for you :)

I want to fill a (allready existing) sql database with 1000 different values. For that I need a txt file that contains the values. So I need a little programm that generates me those values an stores it in a text file. I thought it could be realized with for example 25 firstnames stored in an array, 50 secondnames stored in an array... other values also stored in arrays, and they should be put together with a random function, so that in the end I´ve got 1000 different values

For example the result shall be as follows:

insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('mike', 'miller', 4000, '37745/1467293', 'arrowstreet 5', 'california', NULL);
insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('frank', 'hanson', 1500, '3345/3543657', 'streetstreet 32', 'queens', 1);
insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('fred', 'hamilton', 2000, '3345/65756762', 'streetstreet 34', 'losangeles', 2);
.
.
.

hope that somebody can help me!! thx for your attention!!
0
Comment
Question by:shed7
  • 4
  • 4
  • 2
10 Comments
 
LVL 2

Expert Comment

by:Tols
ID: 9670537
Tell us what You've done already.
0
 

Author Comment

by:shed7
ID: 9670549
sorry I´ve done nothing yet. I just have an sql table which I want to fill with 1000 values. For that I need a txt file in whit those values are stored in like:

insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('mike', 'miller', 4000, '37745/1467293', 'arrowstreet 5', 'california', NULL);
insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('frank', 'hanson', 1500, '3345/3543657', 'streetstreet 32', 'queens', 1);
insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('fred', 'hamilton', 2000, '3345/65756762', 'streetstreet 34', 'losangeles', 2);
.
.
.

I thought, with Java it´s rather easy to realize that.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9670925
Here is a start for you.  It combines two first names and surnames from the arrays in sequence.  Doing this randomly could easily result in duplicates.

You'll need to expand it to fill in all the other fields, but that should be easy from this point ;-)

RandomData.java
------------------------
import java.io.*;

public class RandomData
{
    private String[] FIRST_NAMES = {"Thomas", "Edward", "Henry", "Gordon", "James"};
    private String[] SURNAMES = {"Smith", "Jones", "Brown", "Johnson", "Williams"};
   
    private void init()
    {
        try
        {
            BufferedWriter bw = new BufferedWriter(new FileWriter("datafile.txt"));
            StringBuffer lineOfData;
            for (int i = 0; i < FIRST_NAMES.length; i++)
            {
                for (int j = 0; j < SURNAMES.length; j++)
                {
                    lineOfData = new StringBuffer(FIRST_NAMES[i]);
                    lineOfData.append(",");
                    lineOfData.append(SURNAMES[j]);
                    bw.write(lineOfData.toString(), 0, lineOfData.length());
                    bw.newLine();
                }
            }
           
            bw.close();
        }
        catch(IOException ioe)
        {
            System.err.println("IOE: " + ioe.toString());
        }
    }
   
    public static void main(String[] args)
    {
        new RandomData().init();
    }
}
0
 
LVL 2

Expert Comment

by:Tols
ID: 9671122
For simple import to MySQL You may generate some csv file - text with recordds in rows and fields separated by for ex. tab. This kind of file could be simple imported by sql query.
Code may look like:

public class Generator
{
    public String getRandomFirstName();
    public String getRandomSecondname();
    public String getRandomEarnings();
    public String getRandomTelephon();
    public String getRandomStreet();
    public String getRandomCity();
    public String getRandomNumber();

    public void generateFile(File file)
   {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        String record = "";
        for (int i=0;i<1000;i++)
        {
              record =
                        getRandomFirstName() + "\t" +
                        getRandomSecondname()  + "\t" +
                        getRandomEarnings() + "\t" +
                        getRandomTelephon()+ "\t" +
                        getRandomStreet()+ "\t" +
                        getRandomCity()+ "\t" +
                        getRandomNumber();
              bw.write(record, 0, record.length());
              bw.newLine()
        }
        bw.close();
   }
}
0
 

Author Comment

by:shed7
ID: 9672452
hey thank you guys.
@jimmack: works great, but how does it have to look like, if I want that the output in the txt file is exactly:

insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('mike', 'miller', 4000, '37745/1467293', 'arrowstreet 5', 'california', NULL);

and only the values like 'mike', 'miller', 4000, '37467/394394',... change randomly ? something like:
                    lineofData.append("insert into member (firstname, secondname, earnings, telephon, street, city, number) values ("
                    lineOfData = new StringBuffer(FIRST_NAMES[i]);
                    lineOfData.append(",");
                    lineOfData.append(SURNAMES[j]);
                    bw.write(lineOfData.toString(), 0, lineOfData.length());
                    bw.newLine();

or hmm?? as I said before, I´m a completely newbie in java ;)
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 15

Expert Comment

by:jimmack
ID: 9672540
Very close ;-)

You need to add the code to generate the earnings, telephon, street, city and number values.  How you do this depends on what your record key is (ie. how you determine uniqueness of a record).  If this is just test data and only the names are important, then you could do the following:

    lineOfData = new StringBuffer("insert into member (firstname, secondname, earnings, telephon, street, city, number) values ('";
    lineOfData.append(FIRST_NAMES[i]);
    lineOfData.append("', '");
    lineOfData.append(SURNAMES[i]);
    lineOfData.append("', 4000, '37745/1467239', 'arrowstreet 5', 'california', NULL);");
    bw.write(lineOfData.toString(), 0, lineOfData.length());
    bw.newLine();

A couple of things to note:

1) Be careful about making sure that the single apostrophe is included in the string in the correct place
2) If you don't want to have the same data (other than name) for every line, you'll need to figure out what you want instead.  eg. You could use a random number generator to put in random earnings and telephone numbers.

import java.util.Random;
.
.
private Random random;
.
.
random = new Random();  // If you want the same random sequence every time, use random = new Random(1);
.
.
int earnings = (random.nextInt(5) + 1) * 1000;  // Gives a value of 1000 to 5000

Then you can include the earnings value in the string:

    lineOfData.append(SURNAMES[i]);
    lineOfData.append("', ");
    lineOfData.append(earnings);
    lineOfData.append(", '37745/1467239', 'arrowstreet 5', 'california', NULL);");

Any good ;-) ?
0
 

Author Comment

by:shed7
ID: 9672748
Yes, thats much better!! Although its just a test data I actually want every value as a random value. I´m not shure where I have to place
private Random random;
.
.
random = new Random();  // If you want the same random sequence every time, use random = new Random(1);
.
.
int earnings = (random.nextInt(5) + 1) * 1000;  // Gives a value of 1000 to 5000


and how can I use that random function for the other values telephon, street, city, number ??

oh yes ít´s already very close and I can see the end of the tunnel!! ;)
0
 
LVL 15

Accepted Solution

by:
jimmack earned 250 total points
ID: 9673042
Here's my previous post, updated with the mods.  I've broken down the lineOfData creation so that you can change the individual fields more easily and I've included another random number creation line for the phone number.

If you want to create addresses and states randomly, then you should store some in a String array and pick them out at random, like I've done for a few states.

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

public class RandomData
{
    private String[] FIRST_NAMES = {"Thomas", "Edward", "Henry", "Gordon", "James"};
    private String[] SURNAMES = {"Smith", "Jones", "Brown", "Johnson", "Williams"};
    private String[] STATES={"California", "Ohio", "New York", "Texas"};

    private Random random;
   
    private void init()
    {
        random = new Random(1);
        try
        {
            BufferedWriter bw = new BufferedWriter(new FileWriter("datafile.txt"));
            StringBuffer lineOfData;

            int earnings;
            int phoneNumber;

            for (int i = 0; i < FIRST_NAMES.length; i++)
            {
                for (int j = 0; j < SURNAMES.length; j++)
                {
                    earnings = (random.nextInt(5) + 1) * 1000;
                    phoneNumber = 1000000 random.nextInt(1000000);  // gives values 1000000 to 1999999
                    lineOfData = new StringBuffer(FIRST_NAMES[i]);
                    lineOfData.append(",");
                    lineOfData.append(SURNAMES[j]);
                    lineOfData.append("', ");
                    lineOfData.append(earnings);
                    lineOfData.append(", '");
                    lineOfData.append("37745/");
                    lineOfData.append(phoneNumber);
                    lineOfData.append("', '");
                    lineOfData.append("arrowstreet 5");
                    lineOfData.append("', '");
                    lineOfData.append(STATES[random.nextInt(STATES.length)]);
                    lineOfData.append("', NULL);");
                    bw.write(lineOfData.toString(), 0, lineOfData.length());
                    bw.newLine();
                }
            }
           
            bw.close();
        }
        catch(IOException ioe)
        {
            System.err.println("IOE: " + ioe.toString());
        }
    }
   
    public static void main(String[] args)
    {
        new RandomData().init();
    }
}
0
 

Author Comment

by:shed7
ID: 9676879
hey thank you very much!!!!!! It works great!!
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9677328
:-)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

910 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now