How to remove line from txt file with buffered reader java [duplicate] - java

This question already has answers here:
Find a line in a file and remove it
(17 answers)
Closed 5 years ago.
I need to remove lines from txt file a
FileReader fr= new FileReader("Name3.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
and I don't know the continue of the code.

You can read all lines and store them in a list. Whilst you're storing all lines, assuming you know the line you want to remove, simply check for the lines you don't want to store, and skip them. Then write the list content to a file.
//This is the file you are reading from/writing to
File file = new File("file.txt");
//Creates a reader for the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
//This is your buffer, where you are writing all your lines to
List<String> fileContents = new ArrayList<String>();
//loop through each line
while ((line = br.readLine()) != null) {
//if the line we're on contains the text we don't want to add, skip it
if (line.contains("TEXT_TO_IGNORE")) {
//skip
continue;
}
//if we get here, we assume that we want the text, so add it
fileContents.add(line);
}
//close our reader so we can re-use the file
br.close();
//create a writer
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//loop through our buffer
for (String s : fileContents) {
//write the line to our file
bw.write(s);
bw.newLine();
}
//close the writer
bw.close();

Related

How do I read only one line of text file? [duplicate]

This question already has answers here:
How to read a specific line using the specific line number from a file in Java?
(19 answers)
Closed 5 years ago.
My program is reading all lines in the file but i just need the second one.
String line;
try (
InputStream fis = new FileInputStream(source);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr)) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
If you only need the second line and you are sure the file always has at least two lines, you can just read twice and ignore the first time.
br.readLine(); //read, but ignore
System.out.println(br.readLine()); // read and output

JAVA write new row to .CSV file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 6 years ago.
How can I write a new row of data to a .CSV file that already has data in it. So far my code just clears the file and doesn't actually write anything?
BufferedReader br = null;
BufferedWriter bw = null;
String fileString = "patients.csv";
String fileLine = "";
File file = new File(fileString);
br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter(fileString);
bw = new BufferedWriter(fw);
while((fileLine = br.readLine()) != null){
bw.write(fileLine);
}
br.close();
bw.close();
specify true in the constructor java FileWriter to know that the true and append be added to the end of the file if you place it does not overwrite information
FileWriter fw = new FileWriter(fileString,true);
If you want to append to a file using FileWriter then use this Constructor
As per Javadocs
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
But, back to your code, you will only need to write new data to the FileWriter and not rewrite existing data.

How to make a line as the first line in a TEXT file using Java

I have a text file "test.txt" with the following content
********************
Hi
This is ABC
I learning JAVA and would like to expertize in it.
I joined Stackoverflow today.
********************
My requirement is to make the line #4 - I joined Stackoverflow today. as the first line in test.txt so that the file content is as follows:
********************
I joined Stackoverflow today.
Hi
This is ABC
I learning JAVA and would like to expertize in it.
I joined Stackoverflow today.
********************
Can this be done via code, as I am trying to use various Java Utils, but I am unable to make the line move to the first place.
May not be the best way, but works!
First Delete the line
File inputFile = new File("test.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "I joined Stackoverflow today.";
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"));
}
boolean successful = tempFile.renameTo(inputFile);
writer.close();
reader.close();
Then Append it at the beginning of your file
RandomAccessFile f = new RandomAccessFile(new File("yourtextfile.txt"), "rw");
f.seek(0); // to the beginning
f.write(lineToRemove.getBytes());
f.close();
the input file being used has duplicates records
DETAILS:
aa
bb
aa
gg
bb
bb
To remove duplicates, I am using the following code
File Readfile= new File(n.getProperty("file"));
BufferedReader reader= new BufferedReader(new FileReader(Readfile));
Set<String> lines = new HashSet<String>(10000);
String line;
while((line=reader.readLine())!=null){
lines.add(line);
}
reader.close();
File file =new File("stripduplicates.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath()));
//EDIT done
writer.write("DETAILS:");
for(String unique: lines){
//EDIT done
if(!(unique.startsWith("DETAILS:"))
{
writer.write(unique);
writer.newLine();
}
}
writer.close();
}
The output is coming as needed
DETAILS:
aa
gg
bb

How to replace the star {*} in text file with a number [duplicate]

This question already has answers here:
replace String with another in java
(7 answers)
Closed 3 years ago.
My contents of text file looks something like this
Synonyms of Fluster:
*panic
*perturb
*disconcert
*confuse
......
Now i wish to replace the * with numbers.Something like this.
output
Synonyms of Fluster:
1)panic
2)perturb
3)disconcert
4)confuse
......
Edit:
Integer count = 1;
File input = new File("C:\\Sample.txt");
File output = new File("C:\\output.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
Writer writer =new FileWriter(output);
while((line=reader.readLine())!=null)
{
if(line.contains("*"))
{
line.replace("*",count.toString() );
writer.write(line);
count++;
}
else
{
writer.write(line);
}
}
This is what i had tried before posting question here..But this doesn't seem to work.
Now can somebody help me out..?
You should write a JAVA program.
Here's something that may get you started (rough code):
BufferedReader br = new BufferedReader(new FileReader(file));
//start reading file line-by-line
while ((line = br.readLine()) != null) {
//replace * with whatever you want
// Use a counter to keep track of lines to give corresponding line number
String val = line.replace("*",counterVar.toString());
}
br.close();
Write back to file using BufferedWriter again, wrap it with PrintWriter if you wish to,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outputfile")));
Try something like this (Untested code):
try{
List<String> lines = Files.readAllLines(fileName, Charset.defaultCharset());
for (int i = 0; i< lines.size(); i++) {
lines.set(i, lines[i].replace("*", String.valueOf(i)));
}
} catch (IOException e) {
e.printStackTrace();
}
...//Then save the file

How to set String equal to text in .txt file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
I have a .txt file that I want to save in a String variable. I imported the file with File f = new File("test.txt");. Now I am trying to put the contents of it in a String variable. I can not find a clear explanation for how to do this.
Use a Scanner:
Scanner file = new Scanner(new File("test.txt"));
String contents = file.nextLine();
file.close();
Of course, if your file has multiple lines you can call nextLine multiple times.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}

Categories

Resources