posted 18 years ago
I would not use an ArrayList, I'd use a LinkedList. I'd basically do what the first respondent said, use BufferedReader to read the file line by line into a LinkedList, each line added to the end.
Next, go into the first node of the list and get the length of the first line. Say it's 60. Then:
1. Go to next node and look at the contained string.
2. If the line is less than 60, go to next node.
3. If the line is longer than 60:
a. Split that string into two substrings, one consisting of the first 60 characters and the other consisting of the rest.
b. Replace the contents of the current node with the first subsequence.
c. Insert a new node immediately after the current node and place the second subsequence into that node.
4. Go to step 1.
So let's see how this would work. Say your string is "hi\nthere\nu".
You'd read this in so that the nodes in your LinkedList would contain: "hi", "there", "u".
"hi" is two chars long so your line length is 2. Go to second node. "there" is longer than 2, so you split it into "th" and "ere". "th" replace "there" in this node, and you insert a node after this node containing "ere". Go to next node.
This node contains "ere". It's split into "er" and "e", and the "e" is inserted into the next node.
Next node contains "e". It's less than 2, so skip. Last node contains "u", also less than 2, so skip. You now have, in your LinkedList:
"hi", "th", "er", "e", "u"
The reason you want to use a LinkedList instead of an ArrayList is because a LinkedList is ideal for inserting nodes into the middle...it can be done in constant time (no matter how many nodes in the list, a new node can always be added in a fixed amount of time). An ArrayList, on the other hand, can give you access to any data in constant time, but you cannot insert a node anywhere in constant time. Every time you insert into an ArrayList, you push all the contents down one spot, and they all have to be copied one spot down, one at a time.
sev