Unable to rename file - java

I was trying an exercise of deleting lines from a file not starting with a particular string.
The idea was to copy the desired lines to a temp file, delete the original file and rename the temp file to original file.
My question is I am unable to rename a file!
tempFile.renameTo(new File(file))
or
tempFile.renameTo(inputFile)
do not work.
Can anyone tell me what is going wrong? Here is the code:
/**
* The intention is to have a method which would delete (or create
* a new file) by deleting lines starting with a particular string. *
*/
package com.dr.sort;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RemoveLinesFromFile {
public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) {
String line = null;
BufferedReader rd = null;
PrintWriter wt = null;
File tempFile = null;
try {
// Open input file
File inputFile = new File(file);
if (!inputFile.isFile()) {
System.out.println("ERROR: " + file + " is not a valid file.");
return;
}
// Create temporary file
tempFile = new File(file + "_OUTPUT");
//Read input file and Write to tempFile
rd = new BufferedReader(new FileReader(inputFile));
wt = new PrintWriter(new FileWriter(tempFile));
while ((line = rd.readLine()) != null) {
if (line.substring(0, startsWith.length()).equals(startsWith)) {
wt.println(line);
wt.flush();
}
}
rd.close();
if (!keepOrigFile) {
inputFile.delete();
if (tempFile.renameTo(new File(file))) {
System.out.println("OK");
} else {
System.out.println("NOT OK");
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
finally {
if (tempFile != null && tempFile.isFile()) {
wt.close();
}
}
}
}

I guess you need to close your PrintWriter before renaming.

if (line.substring(0, startsWith.length()).equals(startsWith))
should instead be the opposite, because we don't want the lines that are specified to be included.
so:
if (!line.substring(0, startsWith.length()).equals(startsWith))

Related

Displaying the contents of a textfile by typing the filename in a java program?

Write a program that reads in a file and displays its contents. Get the input filename from the command line. For example, if your program is in the file Display.class, you would enter on the command line:
java Display t1.txt
to display the content file t1.txt.
How can this be done?
you can use FileReader or BufferedReader to read the contents of file. below code may be helpful to you
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Display {
public static void main(String[] args) {
if(args.length > 0) {
String fileName = args[0];
try {
File file = new File(fileName);
if(file.exists() && file.isFile() ) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
System.out.println("FileContents are...");
while((line = br.readLine()) != null) {
System.out.println(line);
}
}else{
System.out.println("File Not Found");
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Read and edit the file from Java

I'm trying to introduce a line break at every 100th character of the line from the existing file.But it doesn't write anything to it. below is the code written in java to read the existing file and write to it with a temporary file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
First off, line.replaceAll does not replace your line variable with the result. Because Strings are immutable, this method returns the new string, so your line should be line = line.replaceAll(....
Second, you're never writing the new String back into the file. Using replaceAll doesn't change the file itself in any way. Instead, try using your bw object to write the new String to the same line.
From what you've published here, you never try to write line back to bw. Try this:
package hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
new Test().replace();
}
public void replace() {
String oldFileName = "d:\\1.txt";
String tmpFileName = "d:\\2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("(.{100})", "$1\n");
bw.write(line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
You never try to write line back to bw;
String#replaceAll will return the copy of the source not the original String;

Code deletes the content of the file rather than replacing a text

In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

The FileReader cannot find my text file

I have a simple text file and for some reason, it cannot be found. I don't see anything wrong with the code because I got it from a site, and I am starting to think that I didn't place the text file in the right place. Any suggestion please?
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MainFavorites {
public static void main(String[] args) throws IOException {
/**
* finds pathway to the file
*/
// File file = new File("icecreamTopping.txt");
// System.out.println(file.getCanonicalPath());
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("icecreamTopping.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
myFileLines.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
int numElements = myFileLines.size();
System.out.println ("there are n lines in the file:" + numElements);
for (int counter = numElements-1; counter >= 0; counter--) {
String mylineout = myFileLines.get(counter);
System.out.println (mylineout);
}
}
}
File content:
1- Blueberry
2- Banana Buzz
3- Cookie Batter
My stack trace is this:
java.io.FileNotFoundException: C:\Users\homar_000\workspace\RankFavorites\icecreamTopping.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at MainFavorites.main(MainFavorites.java:28)
Replace below line
reader = new BufferedReader(new FileReader("icecreamTopping.txt"));
with
reader = new BufferedReader(new FileReader("resources/icecreamTopping.txt"));
and put the file under resources folder that resides parallel to src folder.
Sample code:
Reading a file abc.txt from resources folder
reader = new BufferedReader(new FileReader("resources/abc.txt"));
Here is the project structure
Try below code to find out where it is pointing to file icecreamTopping.txt.
File f=new File("icecreamTopping.txt");
System.out.println(f.getAbsolutePath());
After getting the absolute path, just place the file there.
--EDIT--
As per your last comments, put icecreamTopping.txt file in the project RankFavorites directly as shown in below snapshot and It will definitely solve your problem.
Found out what was the problem. It was unnecessary for me to put the file extension so I removed the .txt because when I kept it, it read it as "icecreamTopping.txt.txt"
Move the text file to java/main/resources folder if you are using Maven or to classes folder, so that it will be in classpath. Then use the following line of code to get the file path. Replace MyClass with your class name. Use the path as argument in FileReader.
String path = MyClass.class.getClassLoader().getResource("text_file.txt").getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
Try to use File class to detect your file in storage:
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
JSONParser parser = new JSONParser();
ObjectMapper mapper = new ObjectMapper();
try {
Object obj = parser.parse(new FileReader("/home/sahan/Desktop/data.json"));
ObjectNode objNode = mapper.convertValue(obj, ObjectNode.class);
System.out.println(objNode);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

How to open a text file?

I can't figure out for the life of me what is wrong with this program:
import java.io.*;
public class EncyptionAssignment
{
public static void main (String[] args) throws IOException
{
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("notepad encypt.me.txt"));
line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
System.out.println(line);
}
}
The error message says that the file can't be found, but I know that the file already exists. Do I need to save the file in a special folder?
The error is "notepad encypt.me.txt".
Since your file is named "encypt.me.txt", you can't put a "notepad" in front of its name. Moreover, the file named "notepad encypt.me.txt" probably didn't exist or is not the one that you want to open.
Additionally, you have to provide the path ( absolute or relative ) of your file if it's not located in your project folder.
I will take the hypothesis that your are on a Microsoft Windows system.
If your file has as absolute path of "C:\foo\bar\encypt.me.txt", you will have to pass it as "C:\\foo\\bar\\encypt.me.txt" or as "C:"+File.separatorChar+"foo"+File.separatorChar+"bar"+File.separatorChar+encypt.me.txt".
If it's still not working, you should verify that the file :
1) Exist at the path provided.
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.exists());
If the path provided is the right one, it should be at true.
2) Can be read by the application
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.canRead());
If you have the permission to read the file, it should be at true.
More informations:
Javadoc of File
Informations about Path in computing
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Reference: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Categories

Resources