How to store characters from a .txt file into a 2D array

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

57 Replies - 9626 Views - Last Post: 12 October 2011 - 02:57 AM Rate Topic: -----

#1 pilaso  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 10-October 11

How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 06:50 AM

I am given a .txt file wherein I have to store it to a 2D array so that I will be able to count the number of columns in the file.

Here it what I have, but I just dont know how to store the characters into the array properly.

public static void main(String args[])throws Exception{
		Print x = Print();

		char[][] sample = a.readFile("sample.txt");

	
	}

	public static void readFile([][]){
	 try{
 
    FileInputStream fstream = new FileInputStream("sample.txt");
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
 
	
    while ((strLine = br.readLine()) != null)   {
      System.out.println (strLine);
	 
    }

    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
	 




This post has been edited by pilaso: 10 October 2011 - 06:52 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How to store characters from a .txt file into a 2D array

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 06:58 AM

One of the more typical ways is to break the line from the file using String.split() method. Something like (in concept),
array[][] = strLine.split();

It's difficult to be more specific without the details of the text data.
Was This Post Helpful? 0
  • +
  • -

#3 pilaso  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 10-October 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:07 AM

My txt file is something like this:

___#___
__#_#__
_#___#_
#######


I was planning to create separate methods for reading the txt file, and then another method to count the number of columns. I Just dont know how to store the characters into a array[][].
Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:12 AM

Still confused.

So is each character in a line of the text file a column? If not, what constitutes a column? Do the text lines contain different numbers of columns?
Was This Post Helpful? 0
  • +
  • -

#5 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 8002
  • View blog
  • Posts: 13,712
  • Joined: 19-March 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:15 AM

What I don't understand here is why you're wanting to store the lines. I could understand counting the characters so you could get your array dimensions right, reading the file into memory just to count the characters in each line seems like a bit of a waste.
Beyond that, a String is a nice flexible wrapper on an array of Characters: it allows for all sorts of operations, you don't need to think about its dimensions, it's all pretty easy to handle. Why would you want to unwrap it to an array of char, which only tells you its maximum length and not the length of its contents?


If you just want to know how many columns there are in the file, presumably you want the maximum line length. Read the file line by line, and get the length of each line. If it's greater than the previous maximum, save it. Now you're done with the the line, according to your requirements above. Toss it over your shoulder and get the next line.

If you want to keep the text in memory, you have a couple of reasonable options. I suppose an array of Strings is one of them, though I usually use an ArrayList if I need to navigate the in-memory text. If you just want to do global operations on the text (character replacements and so forth) then you can just append each line to a StringBuilder and pop out its toString() when you need to write it back to disk.
What I can't see is a case where a 2D array is the right answer.

This post has been edited by jon.kiparsky: 10 October 2011 - 07:17 AM

Was This Post Helpful? 1
  • +
  • -

#6 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:15 AM

If the number of columns is really all you need from the file then you can just read each line in turn, get the length of the string, and update a maxLength variable if it is the longest line so far.

If you really want the char[][] array then you can do something like this:

char[][] toChar2dArray(String[] lines) {
  char[][] result = new char[lines.length][];
  int i = 0;
  for(String s : lines) {
    char[] lineArray = s.toCharArray();
    result[i] = lineArray;
    i++;
  }
  return result;
}


Which I would probably rewrite like this:

char[][] toChar2dArray(String[] lines) {
  char[][] result = new char[lines.length][];
  for(int i = 0; i < lines.length; i++) {
    result[i] = lines[i].toCharArray();
  }
  return result;
}

Was This Post Helpful? 1
  • +
  • -

#7 pilaso  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 10-October 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:16 AM

Yes, each character in a line of the text file is a column, and yes, each line can have different number of columns. The highest number of column is the one that is printed.
Was This Post Helpful? 0
  • +
  • -

#8 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:17 AM

Remember, a 2D array is really just an array of arrays. It's really just Object[] where the Object is a char[].
Was This Post Helpful? 1
  • +
  • -

#9 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 8002
  • View blog
  • Posts: 13,712
  • Joined: 19-March 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:28 AM

View Postpilaso, on 10 October 2011 - 09:07 AM, said:

My txt file is something like this:

___#___
__#_#__
_#___#_
#######


I was planning to create separate methods for reading the txt file, and then another method to count the number of columns. I Just dont know how to store the characters into a array[][].



If you really desperately want to have an array of arrays of char, read each line and call the toCharArray() method on the resulting String:

while (reader.hasNext())
{
  myArrayOfChars[index] = reader.nextLine().toCharArray();
}

Or if you want to do it yourself, you can manually unroll the String into a char array by walking it in a loop:
- get the String from your reader
- get the length of the String, l
- declare an array of char, capacity l
- for i from [0 to l), array[i] = string.charAt(i)

repeat while the reader has Strings in.

You could probably make it even worse - for example, you could omit the call to string.length() and just read characters from the String until you get an exception, but that would really be ridiculous.

Another ridiculous way to do it would be to read nextChar() from the file until you hit a newline. At a newline, make a new array of char and carry on. Remember to write a method to resize the array, in case you run out of space.

But really, all of this is just silliness. There's a reason cfoley and I both posted the same solution at the same time: it's the correct solution.

This post has been edited by jon.kiparsky: 10 October 2011 - 07:29 AM

Was This Post Helpful? 2
  • +
  • -

#10 pilaso  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 10-October 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:31 AM

thank you so much for all the help!

but I still cant print. It says that the error is in x.print(file);

import java.io.*;
class Row 
{
   public static void main(String args[])throws Exception{
	Row x = new Row();
		File file = new File("simple.txt");
	
		
		x.print(file);
   
   }
   
  
  
  
  public static char[][] print(String[] lines) {

  char[][] result = new char[lines.length][];

  for(int i = 0; i < lines.length; i++) {

    result[i] = lines[i].toCharArray();


  }
  return result;
}
}


Was This Post Helpful? 0
  • +
  • -

#11 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:51 AM

That's because the print() method expects a String array but you give it a File object. You need to read in the contents of the file, either with a Scanner or a BufferedReader.

If all you are ever going to do with the file is get the max column width, then read it in and determine the width at the same time.

My guess is that you are eventually going to do something with the file's contents, and that probably (but not necessarily) means storing it. If you need an array of strings then read it in like that. If you need a 2D char array then read it in like that.

The best way to store it depends on what you will eventually do with it.
Was This Post Helpful? 1
  • +
  • -

#12 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 8002
  • View blog
  • Posts: 13,712
  • Joined: 19-March 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:52 AM

The first bug in that method is that it doesn't do what the name says.

If you say you're going to print, then print, as in sending something to an output stream.

The problem your compiler is catching is this:


x.print(file);


This call is illegal, since your method takes an array of String as a parameter.
Was This Post Helpful? 1
  • +
  • -

#13 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 04:12 PM

Please, in future ask on your thread instead of emailing.

I can see from your first post you know how to read all the lines in. One of my posts shows you how to convert Strings into char arrays and store them in a 2D array. All you have to do is merge the two code snippets.
Was This Post Helpful? 0
  • +
  • -

#14 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 8002
  • View blog
  • Posts: 13,712
  • Joined: 19-March 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 06:36 PM

Quote

Please, in future ask on your thread instead of emailing.


As a "Forum Leader" I feel it's my duty to second this. The people who are likely to help you out will see your question if you post it, and they'll likely respond unless someone beats them to it. If they don't respond, it's because they're doing something else, so a PM is a useless nuisance.

And anyway, most questions get at least one response in a few minutes, so you're going to get a much better result by just posting the question.
Was This Post Helpful? 0
  • +
  • -

#15 pilaso  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 10-October 11

Re: How to store characters from a .txt file into a 2D array

Posted 10 October 2011 - 07:27 PM

Im sorry. I will keep that in mind.

but I still dont get it though...

This post has been edited by pilaso: 10 October 2011 - 07:28 PM

Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »