How to delete a specific string in a text file? - java

How can I delete a specific string in a text file?

Locate the file.
File file = new File("/path/to/file.txt");
Create a temporary file (otherwise you've to read everything into Java's memory first).
File temp = File.createTempFile("file", ".txt", file.getParentFile());
Determine the charset.
String charset = "UTF-8";
Determine the string you'd like to delete.
String delete = "foo";
Open the file for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
Open the temp file for writing.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
Read the file line by line.
for (String line; (line = reader.readLine()) != null;) {
// ...
}
Delete the string from the line.
line = line.replace(delete, "");
Write it to temp file.
writer.println(line);
Close the reader and writer (preferably in the finally block).
reader.close();
writer.close();
Delete the file.
file.delete();
Rename the temp file.
temp.renameTo(file);
See also:
The Java Tutorials - Lesson: basic I/O

Related

Update Zip file or files in zip file without extracting zip file using java

I have a zip file called test.zip in that zip file I have 2 files file1.txt and file2.txt.
I want to update file1.txt file and add one file file3.txt iin zip file using core java concepts without extracting zip file.
can anyone suggest which approach i should use for this use case.
thank you in advance.
get the file on what you want to perform operation,
try (FileInputStream fis = new FileInputStream( String fileName = "C:/Users/Administrator/Desktop/log.zip";);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis)) {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
System.out.format("File: %s Size: %d Last Modified %s %n",
ze.getName(), ze.getSize(),
LocalDate.ofEpochDay(ze.getTime() / MILLS_IN_DAY));
}
}
Then get bufferreader object like as below,
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
Once you will have it, You can modify content as,
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());

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

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();

Java read file and send in the server

I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.

Replace Line in File

I have a text file which I have a BufferedReader read from.
String sCurrentLine;
File myFile = new File("/sdcard/file.txt");
BufferedReader buf = new BufferedReader(new FileReader(myFile));
while ((sCurrentLine = buf.readLine()) != null) {
}
What I want to do is read a specific line and then replace it with something else whilst leaving the rest of the file alone. How should I do this?
Create a temporary file
Read through the file file.txt, write the output to the temporary file making the replacement as necessary
Close the file
Delete/backup the original file
Rename the temporary file to the original file

Read and write to file, but overwrites the file

I'm trying to figure out why this doesn't work. All the files which are shown actually exist. The 'logging.toString()' is a .txt file and it reads all the text in the logging and writes it back with the String which I want to be added. Although when I do this, it overwrites it. But I dont want that. Help?
try{
FileWriter fstream = new FileWriter(logging.toString());
BufferedWriter out = new BufferedWriter(fstream);
FileInputStream fstreams = new FileInputStream(logging);
BufferedReader br = new BufferedReader(new InputStreamReader(fstreams));
String strLine;
while ((strLine = br.readLine()) != null){
htmlTextArea = htmlTextArea + strLine + "\n";
}
out.write(htmlTextArea + logto);
out.close();
} catch (Exception ex){}
Why wouldn't it? You don't pass an append flag:
FileWriter(String filename, boolean append)
The API docs are your friend; they're often helpful for understanding behavior.
Change this line
FileWriter fstream = new FileWriter(logging.toString());
to
FileWriter fstream = new FileWriter(logging.toString(), true);
That way, you tell Java you wish to APPEND the file. There's more in the Javadocs for FileWriter.
Because that's the way FileWriter is implemented.
If you want to append, you should use a different constructor: new FileWriter( logging.toString(), true );
If you want to add something to file but not overwrite it use
FileWriter fstream = new FileWriter(logging.toString(),true);

Categories

Resources