Delete and renaming file having issues - java

i got 2 functions which i created 1 is to change Password and 1 to delete the file. so my intention is to run the change password feature first followed by doing the delete file. the code runs properly and creates the new password in a new file. but it does not work when trying to delete the file & renaming need some help pls
public static void replaceAdminPassword()throws IOException{
try {
Scanner read = new Scanner(System.in);
System.out.println("Enter Old Password: ");
String oldPass = read.nextLine();
String UserPHash = Utility.getHash(oldPass);
System.out.println("Enter New Password: ");
String newPass = read.nextLine();
String UserNHash = Utility.getHash(newPass);
read = new Scanner(new File("admin.dat"));
String line;
String[] details;
String input = "";
File fout = new File("out.dat");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
while (read.hasNextLine()){
line = read.nextLine();
details = line.split("\\|");
if(details[0].equalsIgnoreCase(UserPHash)){
input = UserNHash;
bw.write(input);
System.out.println("Password Changed.");
}
}
bw.close();
replaceAdminFile();
}catch (FileNotFoundException ex){
System.out.println("file not found");
}
}
public static void replaceAdminFile(){
File oldFile = new File("admin.dat");
File newFile = new File("out.dat");
oldFile.delete();
newFile.renameTo(oldFile);
}

I would recommend to use new io API instead :
Files.delete(Paths.get("admin.dat"));
Files.move(Paths.get("out.dat"), Paths.get("admin.dat"));
You might want to check the documentation of move and delete.
Don't forget to import java.nio.file.Files and java.nio.file.Paths.

You need to close the Scanner by calling "read.close()" otherwise the file is still open and you can't rename or delete it.

Related

How to stop overwrite txt file and let it write in new line

The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.
public static void main(String[] args) throws IOException {
// TODO code application logic here
int saldo = 10000;
String anw = "j";
int cost;
try{
File folder = new File("folderName");
folder.mkdir();
File f = new File(folder, "file1.txt"); //file to folder
f.createNewFile(); //skapar fil
//Scanner fileIn = new Scanner(f);
System.out.println("File path" +f.getPath());
//.----------------------------------
while(anw.equals("j")){
Scanner in = new Scanner(System.in);
FileWriter fWriter ;// removed null
BufferedWriter writr;// removed null
System.out.println("Ange utgiftspost:"); //post
String post = in.nextLine();
System.out.println("Ange kostnad:"); //kost
cost=in.nextInt();
in.nextLine();
saldo = +saldo -cost;
System.out.println("saldo:" +saldo);
System.out.println("Vill du mata in fler uppgifter? (j/n) :");
anw = in.nextLine();
String fileContent = "---"+post+"---"+cost+"---"+saldo;
fWriter = new FileWriter(f);
writr = new BufferedWriter(fWriter);
writr.write(fileContent);
writr.newLine();
if (anw.equals("n")) {
writr.close();
//writer.close();
//System.out.println("---"+post+"---"+cost+"---"+saldo);
}
} //frågan slut
}//try
//Scanner fileIn = new Scanner(f);
catch(Exception e){
System.err.println(e.getMessage());
}
}
You are defining with each loop new Scanner and *Writer objects which cause the content is overwritten. Define those once and reuse with each iteration.
Scanner in = new Scanner(System.in);
FileWriter fWriter = new FileWriter(f);
BufferedWriter writr = new BufferedWriter(fWriter);
while (anw.equals("j")) {
// ...
}
Don't forget to close the resources after the loop.
In my previous question, I had #ASKW answer working for this problem.
He commented that BufferedWriter for my particular case wouldn't work. But to use FilterWriter alone with append would solve it.

How to remove old data from text file using user input in Java

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

How do I add data to text file and not overwrite what I have in Java

This is my code so far but it overwrites what I have in the text file already. What I want is for it to add it to a new line in the text file.
import java.io.*;
import java.util.Scanner;
public class Login{
public static void main(String[] args) throws IOException {
Scanner s1,s2;
s1 = new Scanner(new FileInputStream("login.txt"));
s2 = new Scanner(System.in);
boolean loggedIn = false;
String name,pword,n,p;
System.out.println("Are you a new user? (Type y for yes or n for no)");
String nU = s2.next();
if (nU.equals("n"))
{
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
while(s1.hasNext()){
name=s1.next();
pword=s1.next();
if(n.equals(name) && p.equals(pword)){
System.out.println("You are logged in.");
loggedIn = true;
break;
}
}
if(!loggedIn)
System.out.println("Incorrect password or username.");
}
else if (nU.equals("y"))
{
Down here is where the problem with my code will be as this is where it is writing it to the file.
PrintWriter out = new PrintWriter("login.txt");
System.out.println("Enter username:");
n=s2.next();
System.out.println("Enter password:");
p=s2.next();
out.append(n);
out.append(p);
out.close();
System.out.println("Account has been created and you are logged in.");
}
else
System.out.println("Invalid response.");
It is advised to use chain of BufferedWriter and FileWriter, and the key point is FileWriter will append String to current file when use the one of its constructor that lets appaneding by adding true to last paramter like
new FileWriter("login.txt", true)
and when we surrounding it with BufferedWriter object in order to be more efficient if you are going to write in the file number of time, so it buffers the string in big chunk and write the big chunk into a file and clearly you can save a lot of time for writing into a file
Note :It is possible not to use BuffredWriter ,but it is advised because of better performance and ability to buffer the big chunk of Strings and write them once
Just change your
PrintWriter out = new PrintWriter("login.txt");
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
Example:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch(IOException e) {
}
It is possible to solve this issue without using BufferedWriter, yet the performance will be low as I mentioned.
Example:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch (IOException e) {
}
Use FileWriter
FileWriter fw = new FileWriter(filename,true);
//the true will append the new data to the existing data
Something like this
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("login.txt", true)))
out.println(n);
out.println(p);
out.close();
Very simple example is this.
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
File file = new File(workingDir+"/WebContent/Files/login.txt");
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
printWriter.println(workingDir);
printWriter.println("Good thing");
printWriter.close();
hope it helps.

Java How to read/write files to/from any user's desktop

I want to read a file from the user's desktop, and then write a new file to the desktop. Below is the code to do this on my own computer, but I'm not sure how to do it for any user.
I found this previously-asked question, but I'm not sure how to implement such a method in Java. Would I possibly use the System.getProperty() method?
Any help or advice is appreciated. Thanks!
public static String [] read()
{
ArrayList<String> fileArrList = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.print("File name > ");
String fileName = scan.nextLine();
try
{
Scanner file = new Scanner(new File("C:\\Users\\pez\\Desktop\\" + fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
fileArrList.add(line);
}
file.close();
String [] fileArr = new String[fileArrList.size()];
fileArr = fileArrList.toArray(fileArr);
return fileArr;
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found");
}
return null;
}
public static void writeNewFile(ArrayList outputArr)
{
try
{
FileOutputStream fos = new FileOutputStream("C:\\Users\\pez\\Desktop\\output.txt", false);
PrintWriter pw = new PrintWriter(fos);
for (Object i : outputArr)
{
pw.println(i);
}
pw.close();
}
catch (FileNotFoundException fnfe)
{
}
}
You can use the system property user.home:
File desktop = new File(System.getProperty("user.home"), "/Desktop");
Scanner file = new Scanner(new File(desktop, fileName));
I assume you know you are limited to windows environments this way.
I'll give you simple examples that you can implement in your project.
To get windows username you can get the property user.name:
System.getProperty("user.name");
To write on a file you can use this simple code:
PrintWriter writer = new PrintWriter("filename.txt", "UTF-8");
writer.println("Some text");
writer.println("Some other text");
writer.close();
To read a text file you can use this:
BufferedReader br = new BufferedReader(new FileReader("/path/to/filename.txt"));
String textLine = null;
while ((textLine = br.readLine()) != null) {
System.out.println(textLine);
}
You can implement all this code in your project easily.
I hope you find this usefull, sorry for my english.

Java file-new updated file appears in a single line

I am trying to update a file using Java with new data. Let 's say I have a txt file where I have saved the following data:
id grade
3498 8
2345 9
5444 7
2222 5
So I am trying to update the grade, depending the id the user has typed, but the new (updated) file has the type that follows:
id grade3498 62345 95444 72222 5
and so on....
I can t find the reason why this is not working, I guessed it has something to do with not adding a new line while re-writing the data, but even if I add new line character ("\n") in outobj.write(fileContent.toString()); nothing changes.
Here is a snippet of my code :
public String check(int num) throws RemoteException
{
String textinLine;
String texttoEdit;
File file=new File ("c:\\students.txt");
FileInputStream stream = null;
DataInputStream in =null;
BufferedReader br = null;
try
{
stream = new FileInputStream(file);
in =new DataInputStream(stream);
br = new BufferedReader(new InputStreamReader(in));
StringBuilder fileContent = new StringBuilder();
if ((num>0) && (num<6001))
{
while ((textinLine=br.readLine())!=null)
{
texttoEdit=Integer.toString(num);
System.out.println(textinLine);
String[] parts = textinLine.split(" ");
if (parts.length>0)
{
if (parts[0].equals(texttoEdit))
{
int value = Integer.parseInt(parts[1]);
value-=2;
String edit=Integer.toString(value);
String newLine = "\n"+parts[0]+" "+edit+"\n";
msg="You can pass2";
fileContent.append(newLine);
fileContent.append("\n"); }
else
{
fileContent.append(textinLine);
fileContent.append("\n");
}
}
}
}
in.close();
FileWriter fstream = new FileWriter(file);
BufferedWriter outobj = new BufferedWriter(fstream);
outobj.write(fileContent.toString());
outobj.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Finally, let me say that the new file is rightly edited, which means that if the user enters the id 3498, the grade value would change to 8-2=6, but the new file will be in a single line, as I explained before.
On some OS (typically Windows) you need to use \r\n for a new line. Even better, you can use:
String newLine = System.getProperty("line.separator");
for the line separator which will adjust depending on the platform it is run on.

Categories