-1

I was trying to remove the first line in text file using java code referencing from this link but still the scanner does not contain any text, so it write nothing in the text file, please help, what is then problem...? here is a peace of code,

    File path=new File("C:/Users/kassim Ismail/workspace/Coding/textdoc.txt");
    Scanner scan=new Scanner(path);
    FileWriter newread=new FileWriter("C:\\Users\\kassim Ismail\\workspace\\Coding\\textdoc.txt");
    BufferedWriter newreader=new BufferedWriter(newread);
    while(scan.hasNextLine()){
    String nextline=scan.nextLine();

    if(nextline.equals("\n")){
        newreader.newLine();
    }else{
    newreader.write(nextline);  
    }
    }
    scan.close();
    newreader.close();
    newread.close();
    }
Community
  • 1
  • 1
kassim
  • 3
  • 2

2 Answers2

0

Right now I don't see any mistake in your code (reader/writer should work). One thing I am unsure about is wether the blank space in your Filepath is problematic or not (Some programs can't work with blank spaces in file paths I am not sure about Java though).

Maybe you could add some System.out.println("") statements for debugging purposes. For Example (testing if the input file exists):

System.out.println("Inputfile exists: "+path.exists())

printing the read line:

System.out.println("Read line: "+nextline)
Mein Name
  • 527
  • 3
  • 14
  • I had already used {system.out.println(nextline) } but it prints nothing, which mean it is empty But before I didn't declare the file I used to declare the path directly into the scanner constructor at that time when {println(nextline)} it was printing the text file path. that it is. – kassim Oct 22 '16 at 22:12
  • So nextline beeing empty is an error? If so the problem is most likely File path = new File("..."); and the result of path.exists() would be interesting. If that returns 'false' there is most likely a problem with the filepath. – Mein Name Oct 22 '16 at 22:24
0
private boolean removeTopLine(File file){
    try{
        boolean status = false;
        Scanner s = new Scanner(file);
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        String content = "";
        int counter = 0;
        while (s.hasNextLine()){
            if (counter > 0){
                content += s.nextLine();
            }
            counter++;
        } 
        writer.write(content);
        writer.close();
        status = true;
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return status;
}

This is a functional code snippet that would delete the first line of a file however there could be debate on efficiency.

paul
  • 96
  • 9