Results 1 to 2 of 2

Thread: [RESOLVED] clear text in a file

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    1,023

    Resolved [RESOLVED] clear text in a file

    i need to know how to find one line in a file and delete that line only.

    like if i type "text" in a textfield then i click a button and it finds the line in a file where it says "text" and after that clears only that line.

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: clear text in a file

    This code should do it:
    Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class Test {
    	public static void main(final String[] args) throws IOException {
    		final Scanner scanner = new Scanner(System.in);
    		String filePath = null;
    		do {
    			filePath = scanner.nextLine();
    		} while (new File(filePath).exists());
    		final String lineToDelete = scanner.nextLine();
    		final BufferedReader reader = new BufferedReader(new FileReader(
    				filePath));
    		final StringBuffer sb = new StringBuffer();
    		while (reader.ready()) {
    			final String currentLine = reader.readLine();
    			if (!currentLine.equals(lineToDelete)) {
    				sb.append(reader.readLine());
    				sb.append(System.getProperty("line.separator"));
    			}
    		}
    		reader.close();
    		final FileWriter writer = new FileWriter(filePath);
    		writer.write(sb.toString());
    		writer.close();
    	}
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width