Renaming and deleting files - java

I am writing a program to find information and remove them from a text file by making a temp file, removing the original one and then renaming the temp to the original file. So far I have achieved to write the program and it works when I compile it using the windows console, but when I try to run the same code in netbeans it does not work because it can't remove and rename the original file. I'm looking for way to solve this problem.
here is code , it works when I compile it using the windows console but not in the netbeans
import java.io.*;
public class rename {
public static String x="1123";
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + "2.tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().contains(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
rename util = new rename();
String jj;
util.removeLineFromFile("File.txt", x);
}
}

Humn... After closing br and pw, try setting them to null and calling System.gc().
Reference: I can't delete a file in java

to rename
public void rename(String old, String newpath) {
try {
File folder = new File(old);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File(old + listOfFiles[i].getName());
f.renameTo(new File(old + "\\" + newpath));
System.out.println(old + "\\" + newpath);
}
}
System.out.println("conversion is done");
} catch (Exception ex) {
Logger.getLogger(CVAdd.class.getName()).log(Level.SEVERE, null, ex);
}
}

Related

Renaming file to existing file java

I am trying to
Create Temp File "Temp Account Info.txt"
Write information from existing Account File "Account Information.txt" TO "Temp Account Info.txt"
Omit certain information
Delete "Account Information.txt"
Rename "Temp Account Info.txt" to "Account Information.txt"
My issue is steps 4 and 5. Nor am I sure if I am ordering it correctly.
The code is provided below.
public static void deleteAccount(String accountNumber) throws Exception {
File accountFile = new File("Account Information.txt");
File tempFile = new File("Temp Account Info.txt");
BufferedReader br = new BufferedReader(new FileReader(accountFile));
FileWriter tempFw = new FileWriter(tempFile, true);
PrintWriter tempPw = new PrintWriter(tempFw);
String line;
try {
while ((line = br.readLine()) != null) {
if(!line.contains(accountNumber)) {
tempPw.print(line);
tempPw.print("\r\n");
}
}
**FileWriter fw = new FileWriter(accountFile);
PrintWriter pw = new PrintWriter(fw);
tempFile.renameTo(accountFile);
accountFile.delete();
fw.close();
pw.close();
tempFw.close();
tempPw.close();
} catch (Exception e) {
System.out.println("ERROR: Account Not Found!");
}
}
The full code can be found at: https://hastebin.com/eposapecep.java
Any help would be greatly appreciated!
I am aware that I do not correctly check for "Account Not Found" and will try to figure this out after the naming issue.
Thanks in advance!
Use the renameTo() method of File.
try {
File file = new File("info.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
File file2 = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file2));
bw.write(str);
br.close();
bw.close();
if (!file.delete()) {
System.out.println("delete failed");
}
if (!file2.renameTo(file)) {
System.out.println("rename failed");
}
} catch (IOException ex) {
ex.printStackTrace();
}
The code above reads the first line of info.txt, writes it to temp.txt, deletes info.txt, renames temp.txt to info.txt

Why is this not reading in?

I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers

Can't Read File After Building in java

hey guys i've this program to read a file
public static String readFileAsString(String filename){
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(filename));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
reader.close();
return sb.toString();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File Not Found","ERROR",JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
and this is my constructor
public tsst() {
initComponents();
JOptionPane.showMessageDialog(null, readFileAsString("test.txt"),"Succes",JOptionPane.DEFAULT_OPTION);
}
and the file is in the application project if i run the file from Netbeans it's work normaly i got what i need but if i build the application so i got the JAR File and i run it i got Error FILE NOT FOUND
and the same in the Writing
public static void writeFile(String canonicalFilename, String text){
File file = new File (canonicalFilename);
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(file));
out.write(text);
out.close();
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
}
Add this line in your readFileAsString method
System.out.println("Current Directory:"+ new File(".").getAbsolutePath());
That will tell you what your application's current directory is. Put your test.txt file in that same directory and you should be able to read it. I'd imagine the output would be different between Netbeans (where you know the file is expected) and when you run the Jar (which could be anywhere).

Failing to print out contents of a file

I'm trying to print out the contents of the file. When I run the program, it doesn't do anything and I'm having trouble figuring out why.
public static void main(String[] args) {
String fileName = "goog.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data + "***");
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Need to give full path of goog.csv file.
Put goog.csv file in workspace .metadata directory
then give full path of your file it will giving output because i tried your code on my system.
I just change your goog.csv file with mine firmpicture.csv file.
public static void main(String[] args) {
String fileName = "FilePath";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data + "***");
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to specify the full path to the file, unless it exists in the present directory.
Try this:
public static void main(String a[]) {
String fileName = "goog.csv";
File f = new File(fileName);
String data = "";
if(f.exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(f));
while((data= br.readLine()) != null) {
if(!(data.length() == 0))
System.out.println(data);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("The file does not exists !!!");
}
}

why it is always showing file is not found

public static void main(String[] args) throws IOException {
String filename = "C:\\audiofile.wav";
InputStream in = null;
try{
in = new FileInputStream(filename);
}
catch(FileNotFoundException ex){
System.out.println("File not found");
}
AudioStream s = null;
s = new AudioStream(in);
AudioPlayer.player.start(s);
}
i have written this code in netbeans. Name of my audio file is audiofile.wav. But it is all time showing the exception "file not found". Can anyone help me ???
root folders in C drive of Windows Vista and above are protected by UAC. This requires you to run the java executable in Administrative mode.
However, you can shift the wav file elsewhere, where UAC will not interfere(like Documents folder of your currently logged in user) or the root of a different drive(Eg. D:\ and E:)
Also, make sure that the audiofile.wav is indeed in the said location(C:\audiofile.wav)
I think first, you should paste your exception code!
then, I think java I/O support the both two way:
"C:/audiofile.wav"
"C:\audiofile.wav"
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
// write your code here
String fileLocation = "C:\\1.diff";
String fileLocation1 = "C:/1.diff";
try {
FileInputStream f = new FileInputStream(fileLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
System.out.println("11111111111111111111111111");
while (line != null) {
// Process line
line = reader.readLine();
System.out.println(line);
}
System.out.println("11111111111111111111111111");
} catch (Exception ex) {
System.out.println(ex);
}
try {
FileInputStream ff = new FileInputStream(fileLocation1);
BufferedReader reader1 = new BufferedReader(new InputStreamReader(ff));
String line1 = reader1.readLine();
System.out.println("2222222222222222222222222");
while (line1 != null) {
// Process line
line1 = reader1.readLine();
System.out.println(line1);
}
System.out.println("2222222222222222222222222");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
it works. I don't know what you did, anyway paste your error msg!
====
```
private static void B() {
String filename = "C:\\test.wav";
InputStream in = null;
try {
in = new FileInputStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
try {
AudioStream s = new AudioStream(in);
AudioPlayer.player.start(s);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
```
it works!
Try just placing your file in a different location and see what happens
ProjectRootDir
audiofile.wav
src
And running this String
String filename = "audiofile.wav";

Categories

Resources