The task: to remove goods from the database by serial number (4 digits). Question: how to read only the first 4 characters in each line, and if these characters are the same, then delete the line? My program searches for the entire string and deletes it:

package org.FinalProgram; import java.io.*; public class SearchDel { public int number; public SearchDel(int number){ this.number = number; } //getters public int getNumber(){ return number; } //setters public void setNumber(int number){ this.number=number; } public void delete() throws IOException{ File inputFile = new File("C:\\data\\data.txt"); File tempFile = new File("C:\\data\\myTempFile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String lineToRemove = "Строка"; String currentLine; while((currentLine = reader.readLine()) != null) { // trim newline when comparing with lineToRemove String trimmedLine = currentLine.trim(); if(trimmedLine.equals(lineToRemove)) continue; writer.write(currentLine + System.getProperty("line.separator")); } writer.close(); reader.close(); boolean successful = tempFile.renameTo(inputFile); } } 

    1 answer 1

    Java String.startsWith () tutorial

    As I understand it, you should use the startsWith method instead of equals.

    startsWith (String prefix) - checks if the string starts with the specified prefix; startsWith (String prefix, int toffset) - checks if the string starts at the specified position from the specified prefix;

    • Can a prefix be an int or just a String? - PoGostu
    • @PoGostu only String. You can write it startsWith(String.valueOf(int)); - jessez
    • Everything turned out) Just why the old file does not delete and the new does not rename? - PoGostu
    • so i have a line boolean successful = tempFile.renameTo (inputFile); Only nothing happens - PoGostu