how to remove lines based on integer n?

I'm trying to alternate a file but keeping some lines intact based on a user input. (Details below code)

public class RemoveLines {
public static void main(String[] args) 
        throws FileNotFoundException {

    // prompt for input file name
    Scanner console = new Scanner(System.in); 
    System.out.print("Type first file name to use: ");
    String filename1 = console.nextLine();
    System.out.print("Type second file name to use: ");
    String filename2 = console.nextLine();
    System.out.println("enter an integer: ");
    int n = console.nextInt();
    Scanner input = new Scanner(new File(filename1));   //put the first file as input
    PrintStream output = new PrintStream(new File(filename2)); //put the second file as output
    int count =0;
    while(input.hasNextLine()){
        count ++;
        while(n<=count){
            output.println(); // this is where i don't know what to place

        }
    }
}   
}

the program should prompt the user to enter 2 file names and an integer n. it should create a second file that contains the first n lines of the first file, while keeping it intact. If the first file contains less than n lines then the second file will contain all the lines of the first file. i've started writing the while loop, but i am not sure what command i should include in order to have the desired output. thank you.

Answers


Have a try with the following code:

 int count = 0;
    while (count < n) {
        if (input.hasNextLine()) {
            output.println(input.nextLine()); // this is where i don't know what to place
            count++;
        }else
        {
            break;
        }

    }

    /**
     * Close scanner 
     */

    input.close();
    console.close();
    output.close();

while(input.hasNextLine()){
   count ++;
   while(n<=count){
      output.println(input.nextLine()); 
   } else {
      break;
   }
}

You should also check the the input file exists. And also you should close your input and output. I will not matter in this trivial case but it's something you should do in more complex applications.


You should open PrintStream with the append option set to true (which is false by default) -

PrintStream output = new PrintStream(new File(filename2, **true**));

Then you can do something like below -

String inputLine = scanner.readLine(); 
output.append(inputLine);

Need Your Help

Rotating Two UIImageView in X Direction

iphone ios ios5 core-animation catransform3d

i wanna rotate two images i put one images behind the other but when i rotate them with the following code the back image will be above the front image

Why doesn't overflow: hidden work in this case?

html css

In the bookmark_matrix in this fiddle