Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] Reading a File

Started by ElCrazon Jul 31, 2002 at 7:23 PM 2 replies 850+ views
Original Post
ElCrazon
ElCrazon
This may sound wierd, but I''m not sure if there is a better way to do it. I have a text file with different numbers from 1-9 in rows of 30 numbers and there are 30 of these rows. Now what I want to do is read them into my program, each line being an array of ints, then once they''ve all be read into different arrays, parse them so if one array = {000000000000000111111111100000} it would create a string like this: " __________ ". that i can display on different lines of my program. Whats the best way to do this or something similar? Thanks.
nonnus29
nonnus29
Welcome to the wonderful world of java file i/o. You can read ints from a datafile, but you can''t use notepad to generate the file; it stores the numbers as character values (bytes). (Yeah I was really bummed when I figured that one out.... You can read and write bytes all day long but its not very convenient, you know?) So, you have to first write the file of ints then you can read it in. Check into DataOutputStream and DataInputStream.
c_wraith
c_wraith
Ok... If I understand you correctly, nonnus'' response is completely unrelated to what you are looking for.


  
public static int [][] readFile(String filename) throws java.io.IOException
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(filename));

int [][] result = new int[30][30];
for (int i = 0; i < 30; i++)
{
String line = br.readLine();
for (int j = 0; j < 30; j++)
{
result[i][j] = line.charAt(j) - ''0'';
}
}
return result;
}
finally
{
if (br != null)
try { br.close() }
catch (java.io.IOException e) {}
}
}

public static String [] convert(int [][] lines)
{
char [] table = {'' '', ''_'', ... fill in the rest of the values here};

String [] result = new String [lines.length];
for (int i = 0; i < lines.length; i++)
{
StringBuffer temp = new StringBuffer();
for (int j = 0; j < lines[i].length; j++)
{
temp.append(table[lines[i][j]]);
}
result[i] = temp.toString();
}
return temp;
}


Something like that should do what you need... I haven''t tested it, so be very suspicious if it compiles on the first try.
ElCrazon
ElCrazon
Ahh thats just what I was trying yo make my self, I''m new to java i/o somine didn''t work very well. Thanks alot, I''ll come back and tell you how it worked. Thanks alot.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.