0

First of, I don't know how a.db file stores it data. If it does it in one line, or over many lines. Probably it does some difference from how to solve the problem. the problem I'm facing is that I don't know how much data the file contains, only that it will be a date, time, and a description for x number of events in the form given below. I have to convert the text into strings and put them in an array, but I don't know how to separate the text. When I tried I just ended up with one long string.

Can anybody help me?

01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home

what I want:

array[0] = "01.01.2015|07:00-07:15|get up"
array[1] = "01.01.2015|08:00|get to work"
array[2] = "01.01.2015|08:00-16:00| work"
array[3] = "01.01.2015|16:00-16:30| go home"

string table[] = new String [100];

void readFile(String fileName){
  String read = "";
  try {
    x = new Scanner (new File(fileName));
  }
  catch (Exception e) {
  }
  while (x.hasNext()) {
  read += x.nextLine(); 
  }             
}
  • Is your first block of text ("get up, get to work, ...") the actual file content or is it a copy/paste from a database prompt? – aioobe Nov 25 '14 at 10:36
  • If you dont know how big the .db file is, dont use an array of string, use an ArrayList – julien carax Nov 25 '14 at 10:38

4 Answers4

2

Assuming here that your first code-block is in fact a copy of the file you're trying to read, you can do:

Scanner s = new Scanner(new File("file1.txt"));
List<String> lines = new LinkedList<>();
while (s.hasNextLine())
    lines.add(s.nextLine());

If you really want to work with arrays and not lists, you can do

String[] table = lines.toArray(new String[lines.size()]);

after the loop.

If you're fortunate enough to work with Java 8, you can use:

List<String> lines = Files.lines(Paths.get("big.txt"))
                          .collect(Collectors.toList());

Again, if you really want to work with an array, you can convert the list using lines.toArray.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • A `LinkedList` should be more appropriate here (due to multiple `add()`), isn't it ? – NiziL Nov 25 '14 at 10:42
  • @Nizil Isn't. ArrayList is faster and have lower memory consumption. – talex Nov 25 '14 at 10:56
  • @talex I agree for the memory consumption, but `ArrayList` isn't always faster (see [this question](http://stackoverflow.com/questions/10656471/performance-differences-between-arraylist-and-linkedlist)). In this case, I suppose it's depends on the numbers of lines to read and on the initial capacity of the list. – NiziL Nov 25 '14 at 11:01
  • @Nizil unfortunately answer is wrong, But it doesn't matter because in our case we append not insert. This operation have constant amortized complexity for ArrayList. – talex Nov 25 '14 at 11:13
  • I did benchmarks before changing from ArrayList to LinkedList. (I thought ArrayList would be faster in practice.) But LinkedList won on input larger than about half a million lines :-), @talex, is something wrong with my answer? – aioobe Nov 25 '14 at 11:25
  • @aioobe I'm surprised. Have no time to create benchmark myself. Only reason I can think about it is you going to major GC in case of ArrayList slightly early. Try to loop you benchmark and look how figures changing – talex Nov 25 '14 at 11:40
  • I don't understand why you're surprised. In a linked list, all you have to do to append is to change the last elements next-reference to point to the element to insert. In case of an ArrayList you have to (once in a while) allocate a whole new array, and copy over the old content to the new (larger) array. Sure, you don't have to do it very often, but it should be evident that you're bound to be slower than a LinkedList at some point. – aioobe Nov 25 '14 at 11:55
1

Since Java 8 you can use Paths.get(String first, String... more), Files.lines(Path path), and Stream.toArray():

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SOPlayground {

    public static void main(String[] args) throws Exception {

        Path path = Paths.get("/tmp", "db.txt");
        Object[] lines = Files.lines(path).toArray();

        System.out.println(lines.length);
        System.out.println(lines[0]);
        System.out.println(lines[lines.length - 1]);
    }
}

Output:

4
01.01.2015|07:00-07:15|get up
01.01.2015|16:00-16:30| go home
0

Try this solution using arrays:

code

Scanner sc = new Scanner(new File("file.txt"));
int index;
String[] arr = new String[1];
for(index = 0; sc.hasNextLine(); index++) {
    arr = Arrays.copyOf(arr, index + 1);
    arr[index] = sc.nextLine();
}

for(int i = 0; i<arr.length; i++) {
    System.out.print(arr[i] + "\n");
}

I have used arr = Arrays.copyOf(arr, index + 1) to increase the size of the array to add next element.

Output

01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
Community
  • 1
  • 1
Johny
  • 2,128
  • 3
  • 20
  • 33
  • Uhm, but the OP said he didn't know how many records the database had up front. You assume that it's at most 10! – aioobe Nov 25 '14 at 10:52
  • @aioobe i have made some changes now it can accept any size. But i dont think its a good method. – Johny Nov 25 '14 at 11:00
0

Well, it took me some houres. Thanx to all who lended a hand. This was what I got in the end.

  int i=0;
  String array [] new String [100]
  try {
  FileReader textFileReader= new FileReader (fileName);
  BufferedReader textReader= new BufferedReader(textFileReader);
  boolean continue = true; 
    while (continue) {
      String text = textReader.readLine();
        if (text != null){
        array[i] = text;
        i++;
      }else {
     continue = false;
     }
   }
 }catch (Exception e) {}