Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i want to split a file. i have this in my file called data.txt:

ab
cd
ef
gh
ij
kl
mn
op
qr

so i have tried some coding. but when i tried to split them but it only read this:

ab
ef
ij
mn
qr

this is my code:

BufferedReader in = null;
try {
    in = new BufferedReader(new FileReader(data));
    String read = null;
    while ((read = in.readLine()) != null) {
        read = in.readLine();
        String[] splited = read.split("\n");
        for (int z = 0; z<splited.length; z++)
        System.out.println (splited[z]);
        }

} catch (IOException exc) {
    System.out.println("There was a problem: " + exc);
    exc.printStackTrace();
} finally {
    try {
        in.close();
    } catch (Exception exc) {
    }

what is wrong with this code?

share|improve this question
1  
You're reading the file line by line (i.e. the name readLine()) ... there's nothing to split (ignoring the other issues you have) –  Brian Roach 18 mins ago
add comment

3 Answers

Every time you are getting two line in single iteration

while ((read = in.readLine()) != null) {
      //read = in.readLine();

instead of

 while ((read = in.readLine()) != null) {
      read = in.readLine();
share|improve this answer
    
yup. done it. thanks :) –  rilakkuma 12 mins ago
add comment
while ((read = in.readLine()) != null) {
    read = in.readLine();

You are reading from the file twice every iteration, overwriting read the second time, causing you to skip every other line. Just omit the second read = in.readLine(); and your code will work fine.

share|improve this answer
    
i didnt notice the small mistake. it works! thank you :) –  rilakkuma 14 mins ago
add comment

what is wrong is that you have two

read = in.readLine();

instead of one

share|improve this answer
    
i didnt notice that. thank you :) –  rilakkuma 13 mins ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.