FileWriter and PrintWriter won't output to file - java

I have this code
public User createnewproflie() throws IOException
{
FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
String filename= "users.txt";
Scanner userFile = new Scanner(filename); //creates new obj that reads from file
User usr=new User(); //creates new user istance
String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname
userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0"); //writes usrname in file
userfile.flush();
usr.setName(usrname); //gives usr the selected usname
return usr;
}
and it doesn't output on the file... can someone help please?
i knew that flush would output all of the buffered text but it doesn't seem to work for some strange reason...

You can use a String with a FileWriter but a Scanner(String) produces values scanned from the specified string (not from a File). Pass a File to the Scanner constructor (and it's a good idea to pass the same File to your FileWriter). And you need to close() it before you can read it; maybe with a try-with-resources
File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
PrintWriter userfile = new PrintWriter(fwriter);) {
// ... Write stuff to userfile
} catch (Exception e) {
e.printStackTrace();
}
Scanner userFile = new Scanner(f);
Finally, I usually prefer something like File f = new File(System.getProperty("user.home"), "users.txt"); so that the file is saved in the user home directory.

Related

Java functions delete() and renameTo() not deleting nor renaming

public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.

How do I write to a new line using FileWriter in Java? [duplicate]

This question already has answers here:
Create a new line in Java's FileWriter
(10 answers)
Closed 5 years ago.
I've been trying to make a simple bank account in Java and want to save the inputted users' name into a .txt doc. Only problem is that the name is replaced on the first line of the text doc each time I run the code.
package bank.account;
import java.util.Scanner;
import java.io.*;
public class ATM
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
BankAccount userAccount = new BankAccount();
System.out.println("Please enter your name in order to make a new account:");
String fileName = "name.txt";
try {
FileWriter fileWriter =
new FileWriter(fileName);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
String name = sc.nextLine();
userAccount.setaccName(name);
bufferedWriter.write(userAccount.getaccName());
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
}
System.out.println("Please enter the amount you would like to deposit");
double money = sc.nextDouble();
userAccount.deposit(money);
System.out.println(userAccount.getaccBalance());
System.out.println(userAccount.getaccName()+ " your balance is " + userAccount.getaccBalance());
}
}
You're overwriting the file contents due to the use of new FileWriter(fileName); (read the JavaDoc on that class/constructor). Use new FileWriter(fileName, true); to append to the file instead.
Also note that you'd need to append a newline character ("\n") before the name if the file is not empty otherwise you'll get all the names in one line.
This Code will open or create a file and append the new text into a new line.
PrintStream fileStream = new PrintStream(new File("a.txt"));
fileStream.println(userAccount.getaccName());
Also you can create the FileWriter with the param "append = true" and then the outcome will just be appended into a new line.
// FileWriter(File file, boolean append)
FileWriter fileWriter =
new FileWriter(filePathName, shouldAppend);

Multiple Over writes using FileWriter in Java

Im trying to read N different CSV files containing stock price data. I want to extract one particular column from each file and showcase those columns in a single CSV file.
The issue is the combined file contains only the written data from the first file I give as input i.e. that data is not being overwritten in the iteration of my loop.
Can someone help? Or suggest a new method?
public static void main(String[] args) throws IOException
{
int filecount=0;
System.out.println("Enter Number of Files");
Scanner stream =new Scanner(new InputStreamReader(System.in));
filecount= Integer.parseInt(stream.next());
File file2 = new File("Combined_Sym.csv");
FileWriter fwriter= new FileWriter("Combined_Sym.csv",true);
PrintWriter outputFile= new PrintWriter(fwriter);
int i;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
Scanner inputStream2= new Scanner(file2);
if(!inputStream2.hasNext()){
outputFile.println(fileName);
}
else
{ String header=inputStream2.next();
System.out.println(header+","+fileName);
outputFile.println(header+","+fileName);
}
while(inputStream.hasNext())
{
String data= inputStream.next();
String[] values = new String[8];
values = data.split(",");
String sym=values[7];
if(!inputStream2.hasNext())
outputFile.println(sym);
else
{
String data2= inputStream2.next();
outputFile.println(data2+","+sym);
System.out.println(data2+","+sym);
}
}
inputStream.close();
inputStream2.close();
outputFile.close();
}
}
}
Can you try changing :
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
to
File file;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
file = new File(fileName);

How to capture the file name from the server dynamically when some one uploads it

Below is the code to read the file from the server. I Want to read & convert the file dynamically (not hard coded )into different file format(CSV). Could anyone please guide me to capture the uploaded file name dynamically.
try
{
//creating File instance to reference text file in Java
String str1=null;
String str2=null;
String str3=null;
int cnt=0,len1=0,len2=0;
File text = new File("C:\\Petty Ascii Detail.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
File file = new File("C:\\Test\\Write1.txt");
//if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
cnt=line.length();
for(int i=0;i<3;i++)
{
if (Character.isDigit(line.charAt(i)))
str1=line;
else
str2=line;
}
len1=str1.length();
len2=str2.length();
if(len1!=len2)
{
str3=str1+str2;
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str3);
bw.newLine();
System.out.println("Done");
bw.close();
}
lineNumber++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions are really appreciated.
Thanks,
Balaji

How to get a nextLine in the txt file after user inputs string?

Just started coding and found my self overwhelmed with different types of writing to a file. I'm using File and PrintStream library. My issue is that after user is done with typing notes and reopens the file, the file is overwritten. I wish to add just a nextLine function so when the file is opened again we just add text to line2. Thank you in advance.
This is my piece of code:
if(userOption.equals("open") || userOption.equals("OPEN") ){
System.out.print("Please enter the name of the file you want to open : ");
fileNameOpen = kybd.nextLine();
File input = new File( fileNameOpen );
PrintStream print = new PrintStream( input );
System.out.print("Now you can start typing your notes: ");
// print.println(userNotes = kybd.nextLine());
print.println(userNotes = kybd.nextLine());
print.close();
}//end of if
If you just want something simple, this will work:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameOpen , true)));
userNotes = kybd.nextLine()
out.println(userNotes);
out.close();
} catch (IOException e) {
//oh noes!
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).
Of course you will need to incorporate this into your logic.
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(fileNameOpen, true)));
The second argument in the FileWriter will allow you to append a line
if(userOption.equals("open") || userOption.equals("OPEN") ){
System.out.print("Please enter the name of the file you want to open : ");
Scanner kybd = new Scanner(System.in);
String fileNameOpen = kybd.next();
kybd.nextLine();
try{
String data = " This content will append to the end of the file";
File file = new File(fileNameOpen);
// if file does not exist create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fWriter = new FileWriter(file.getName(),true);
BufferedWriter writer = new BufferedWriter(fWriter);
writer.write(data);
writer.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}//end of if

Categories

Resources