file delete and rename not working - java

Here is the code but it does not delete storedIp file and rename tempFile to storedIP. Both file exist
String host=ipParsing(hostName);
File tempFile= new File("tempFile.txt");
File strFile = new File("StoredIp.txt");
BufferedReader bufferReader = new BufferedReader( new FileReader(strFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line;
while ((line = bufferReader.readLine()) != null) {
if(host.equals(line))
{
found=true;
line="";
}
bw.write(line);
if(!line.equals(""))
bw.newLine();
}
bw.close();
bufferReader.close();
strFile.delete();
tempFile.renameTo(new File ("StoredIP.txt"));

Well, a call to File.delete() does not necessary delete the file.
As the JavaDoc says: be sure to check the return value.
Ignoring this (like you did) is a common source of errors.

One occasion where this delete/renameTo easily goes awry, is when the files are in use. A solution seen consists of using an additional lock file. Too complicated for such a simple thing.
Using an embedded database, like java's own Derby, which is not that difficult. The database needs no extra provision. There are good tutorials with simple example code.

Related

Why does introducing a FileWriter delete all the content in the file?

I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)

I can't read a text file in GWT

I am developing a project with GWT and Netbeans. I have an RPC. I have put a text file in the server package "org.myname.server" and I want to read it with a server side method belonging to the class GWTServiceImpl. The text file and the file GWTServiceImpl.java are in the same package. The code is the following:
String text="";
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null)
{
text=text+line;
System.out.println("here is the line: "+line);
}
br.close();
}
catch (Exception e) { }
return text;
It says that it can't access the file. I haven't included the entire path because the file is in the same folder of the method. So why doesn't it work?
File paths aren't relative to “classes”, but to the “current working directory”, so it'll depend how your server is launched, and will likely be different in development and production.
If the file is packaged as a resource in your webapp, then use the appropriate way of loading it: if it's in WEB-INF/classes or in a JAR in WEB-INF/lib, then use getClass().getResourceAsStream("file.txt"); otherwise use ServletRequest#getResourceAsStream().
Yes Thomas is right. So in order to create the buffered reader the code is the following:
InputStream is= getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));

Java - open txt file and clear all multiple spaces

I have a txt file and what I am trying to do is open it and delete all multiple spaces so they become only one. I use:
br = new BufferedReader(new FileReader("C:\\Users\\Chris\\Desktop\\file_two.txt"));
bw = new BufferedWriter(new FileWriter("C:\\Users\\Chris\\Desktop\\file_two.txt"));
while ((current_line = br.readLine()) != null) {
//System.out.println("Here.");
current_line = current_line.replaceAll("\\s+", " ");
bw.write(current_line);
}
br.close();
bw.close();
However, as it seems correct according to me at least, nothing is written on the file. If I use a system.out.println command, it is not printed, meaning that execution is never in the while loop... What do I do wrong? Thanks
you are reading the file and at the same time writing contents on it..it is not allowed...
so better way to read the file first and store the processed text in another file and finally replace the original file with the new one..try this
br = new BufferedReader(new FileReader("C:\\Users\\Chris\\Desktop\\file_two.txt"));
bw = new BufferedWriter(new FileWriter("C:\\Users\\Chris\\Desktop\\file_two_copy.txt"));
String current_line;
while ((current_line = br.readLine()) != null) {
//System.out.println("Here.");
current_line = current_line.replaceAll("\\s+", " ");
bw.write(current_line);
bw.newLine();
}
br.close();
bw.close();
File copyFile = new File("C:\\Users\\Chris\\Desktop\\file_two_copy.txt");
File originalFile = new File("C:\\Users\\Chris\\Desktop\\file_two.txt");
originalFile.delete();
copyFile.renameTo(originalFile);
it may help...
There are few problems with your approach:
Main one is that you are trying to read and write to same file at the same time.
other is that new FileWriter(..) always creates new empty file which kind of prevents FileReader from reading anything from your file.
You should read content from file1 and write its modified version in file2. After that replace file1 with file2.
Your code can look more or less like
Path input = Paths.get("input.txt");
Path output = Paths.get("output.txt");
List<String> lines = Files.readAllLines(input);
lines.replaceAll(line -> line.replaceAll("\\s+", " "));
Files.write(output, lines);
Files.move(output, input, StandardCopyOption.REPLACE_EXISTING);
You must read first then write, you are not allowed to read and write to the same file at the same time, you would need to use RandomAccessFile to do that.
If you don't want to learn a new technique, you will need to either write to a separate file, or cache all lines to memory(IE an ArrayList) but you must close the BufferedReader before you Initialize your BufferedWriter, or it will get a file access error.
Edit:
In case you want to look into it, here is a RandomAccessFile use case example for your intended use. It is worth pointing out this will only work if the final line length is less than or equal to the original, because this technique is basically overwriting the existing text, but should be very fast with a small memory overhead and would work on extremely large files:
public static void readWrite(File file) throws IOException{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
String newLine = System.getProperty("line.separator");
String line = null;
int write_pos = 0;
while((line = raf.readLine()) != null){
line = line.replaceAll("\\s+", " ") + newLine;
byte[] bytes = line.getBytes();
long read_pos = raf.getFilePointer();
raf.seek(write_pos);
raf.write(bytes, 0, bytes.length);
write_pos += bytes.length;
raf.seek(read_pos);
}
raf.setLength(write_pos);
raf.close();
}

BufferedReader then write to txt file?

Is it possible to use BufferedReader to read from a text file, and then while buffered reader is reading, at the same time it also storing the lines it read to another txt file using PrintWriter?
If you use Java 7 and want to copy one file directly into another, it is as simple as:
final Path src = Paths.get(...);
final Path dst = Paths.get(...);
Files.copy(src, dst);
If you want to read line by line and write again, grab src and dst the same way as above, then do:
final BufferedReader reader;
final BufferedWriter writer;
String line;
try (
reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
doSomethingWith(line);
writer.write(line);
// must do this: .readLine() will have stripped line endings
writer.newLine();
}
}
To directly answer your question:
you can, and you can also use BufferedWriter to do so.
BufferedReader br = new BufferedReader(new FileReader(new File("Filepath")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String l;
while((l=br.readLine())!=null){
... do stuff ...
bw.write("what you did");
}
bw.close();
If you just need to copy without inspecting the data, then it's a one liner:
IOUtils.copy(reader, printWriter);
Yes. Open the BufferedReader, and then create a PrintWriter. You can read from the stream as you write to the writer.

How do i read multiple lines from a file into a string to put in jTextArea?

ive tried many different things and this is the only thing that has worked with reading one line from a file so far...
try{
FileInputStream fstream = new FileInputStream("./Saves/Body.sav");
BufferedReader br = new BufferedReader(new InputStreamReader(infstream);
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
w1.Body = strLine;
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
I am trying to create a load function so i can load text from a file onto a string onto a jTextArea... Without any sort of openfiledialog
I'd personally use Guava:
File file = new File("Saves", "Body.sav");
String text = Files.toString(file, Charsets.UTF_8);
That's assuming it's a UTF-8 file, of course. Adjust accordingly.
Your current code has a number of issues:
It creates a DataInputStream for no obvious reason
You probably don't gain much from using BufferedReader
You're not specifying the character encoding, so you're getting the platform default, implicitly, which is almost never a good idea.
You're closing in which is in the middle of the chain of inputs for some reason... I'd expect to close either br or fstream
You're only closing in if there's no exception (use a finally block or a try-with-resources statement if you're using Java 7)
You appear to have a field called Body, violating Java naming conventions
You're catching Exception rather than IOException - prefer to catch specific exceptions
You're "handling" the exception by effectively ignoring it, which is almost never appropriate. (The code which reads a file is very rarely the right code to decide what to do with an exception.)
How do i read ... put in jTextArea?
Ignoring the entire middle of that statement, I suggest.
File file = new File("./Saves/Body.sav");
FileReader fileReader = new FileReader(file);
textArea.read(fileReader, file);
You can use a StringBuilder (or the synchronized version StringBuffer) and keep appending strLine to it. Declare it this way:
StringBuilder s = new StringBuilder();
and in the while loop:
s.append(strLine + "\n");

Categories