I am generating random numbers and want to write them into a file. But its writing them in binary and I am not able to open them using a text editor. How do I write them in Ascii?

Also what is the fastest method to write them into a file? I want to generate 500MB data

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

public class BitsToFile {
	public static void main(String arg[])
		BufferedWriter out;
		Random num=new Random();
		int Size=100;
		int x=0;
		int y[]=new int[Size];
		String S;
		try {
				            out = new BufferedWriter(new FileWriter("randomSample.txt"));
				            for (int i=0; i<Size; i++)
			        }catch(IOException e)
				            System.out.println("There was a problem:" + e);


Recommended Answers

All 7 Replies

If you write the number out as a string rather than an int, it will be in ASCII. For example:

int number = 5;
String text = "" + number;

Since writing to a file is much slower than storing data in memory, you might want to create a buffer of, say, 1,000 elements. Fill the buffer and then flush it out to the file in a loop until you get as much data as you need. You can experiment with larger sized buffers, but eventually you will run out of memory if the buffer gets too big.

done! thanks :)

Is there any faster method to write than what I have done?

Sorry, I was editing my post as you responded. Please see above.

I havent used buffers till now as such so dont have much idea about it.
But if I write the data into a buffer first and then write it into a file how will it reduce the time?

This is like assigning a number to a char variable - it will interpret it as the ASCII value. As kremerd said - you need to convert them into a String.

Each time you write to the file there is overhead involved in spinning up the disk, positioning the write head, etc. So if you can minimize disk writes, your process will be faster. It is much better (faster) to write one 1,000-byte array to a file than to write 1,000 one-byte items.

ok.. so a buffer writes the data in one go..didnt know that..will try it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.