Remove specific line from txt file - java

Hello i need to delete a specific line from text file after ID search p.g. ID=2
students.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
And after search and delete to get:
students.txt
1,Giannis,Oreos,Man
3,Maria,Oaka,Woman
But is not working properly
Code so far:
#FXML
TextField ID2;
#FXML
public void UseDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = ID2.getText();
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);
}

If you want to remove a line by a line number I guess you can do a change to your code like this. You can give the int value of Id to the lineToRemove variable instead of my hard coded value
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
new A().useDelete();
}
public void useDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
int lineToRemove = 2;
String currentLine;
int count = 0;
while ((currentLine = reader.readLine()) != null) {
count++;
if (count == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
}

Related

How can I delete lines of data in textfile using java? eg. my textfile is data.txt

From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);

java homework with word replacement

Hello can someone help me? The point of the homework is to read a file then create another file where it replaces all of the words "is" with "was", i have all this done but I am also not sopposed to replace words that have"is" in them, for example: "this, isthmus".
import java.io.*;
import java.util.*;
public class WordChange {
public static void main(String[]args) throws Exception {
FileReader fr = null;
FileWriter fw = null;
try
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the name of the text file: ");
String fileName=keyboard.nextLine();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String replacedtext=oldtext.replaceAll("is ","was ");
FileWriter writer = new FileWriter("output.txt");
writer.write(replacedtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
just a guess here but instead of
String replacedtext=oldtext.replaceAll("is ","was ");
would this work
String replacedtext=oldtext.replaceAll(" is "," was ");
Im just guessing let me know if it works

extract a part of txt file from String name to an empty line

I want to extract a part of a text file beginning with a String name and ending with an empty line
Here is what I tried:
public File CreateSubscripberFile(File file,String name) throws IOException
{
FileWriter fw = new FileWriter(f);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
if(line.equals(name))
{
while (((line = br.readLine()) != null) && (!(line.equals("\n"))))
{
fw.write(line);
System.out.println(line);
}
}
}
br.close();
fr.close();
fw.close();
return f;
}
but I get the original file as result!
Try to replace:
(line = br.readLine())!=null)
with:
(!(line = br.readLine()).equals(""))
null in this example would mean 'there is not more lines', and .equals(""), looks for empty line.
it's done by edit he code like this
public File CreateSubscripberFile(File file,String name,String fname) throws IOException
{
File f= new File(fname);
FileWriter fw = new FileWriter(f);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null){
if(line.equals(name))
{
String line1 = br.readLine() ;
while(line1 != null && !line1.isEmpty() )
{
System.out.println(line1);
line1=br.readLine();
}
}
}
br.close();
fw.close();
return f;
}

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

How can I ignore a blank line in a srt file using Java

I have a srt file like below and I want to remove blank line : in line no 3
**
1
Line1: 00:00:55,888 --> 00:00:57,875.
Line2:Antarctica
Line3:
Line4:2
Line5:00:00:58,375 --> 00:01:01,512
Line6:An inhospitable wasteland.
**
FileInputStream fin = new FileInputStream("line.srt");
FileOutputStream fout = new FileOutputStream("m/line.srt");
int i = 0;
while(((i =fin.read()) != -1)){
if(i != 0)
fout.write((byte)i);
}
There you go. Steps:
1) FileInputStream fin = new FileInputStream("line.srt"); this is to get the file to a bufferedreader in the next step
2) BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); get the text file to a buffereader
3) PrintWriter out = new PrintWriter("newline.srt"); use a print writer to write the string of every line in the new text file
4) String line = reader.readLine(); read next line
5) while(line != null){
if (!line.trim().equals("")) { check that line is not null and that line is not empty
6) out.println(line); write line (not empty) to the output .srt file
7) line = reader.readLine(); get new line
8) out.close(); close PrintWriter in the end...
import java.io.*;
class RemoveBlankLine {
public static void main(String[] args) throws FileNotFoundException, IOException{
FileInputStream fin = new FileInputStream("line.srt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
PrintWriter out = new PrintWriter("newline.srt");
int i = 0;
String line = reader.readLine();
while(line != null){
if (!line.trim().equals("")) {
out.println(line);
}
line = reader.readLine();
}
out.close();
}
}
INPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
OUTPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
By the way, make sure you are clear when you ask your questions, because the way you state your problem I assumed Line1, Line2, etc are part of your input file, and I have prepared another solution which I had to change... Make sure you are clear and precise so that you get the proper answers !
You can try something like :
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("line.srt"));
bw = new BufferedWriter(new FileWriter("m/line.srt"));
for(String line; (line = br.readLine()) != null; ) {
if(line.trim().length() == 0) {
continue;
} else {
bw.write(line);
bw.newLine();
}
}
bw.flush();
bw.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hope this help
public static void main(String[] args) throws FileNotFoundException, IOException {
Path myPath = Paths.get("e:\\", "1.txt");
List<String> ls ;
ls = Files.readAllLines(myPath, StandardCharsets.US_ASCII);
PrintWriter out = new PrintWriter("e:\\2.txt");
for (int i = 0; i < ls.size(); i++) {
String []temp = ls.get(i).split(":");
if(temp.length>1) {
out.println(ls.get(i));
}
}
out.close();
}

Categories

Resources