Java deletes my file and creates a new one - java

I am trying to finish a bank accounts homework assignment. I have a text file, "BankAccounts.txt" which is created if there is no file with that name. However, if the file exists, I do not create it. But Java desides to delete all my code inside of it :(. Can you help me identify why this happens? Thanks <3
Code:
static Scanner keyboard = new Scanner(System.in);
static File file;
static PrintWriter Vonnegut; //a great writer
static FileReader Max;
static BufferedReader Maxwell;
public static void main(String[] args) {
initialize();
}
static void initialize(){
try { // creating banking file
file = new File("src/BankAccounts.txt");
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
Max = new FileReader("src/BankAccounts.txt");
Maxwell = new BufferedReader(Max);
//get list of usernames and passwords for later
usernames = new String[countLines() / 5];
passwords = new String[usernames.length];
checkingAccounts = new String[usernames.length];
savingsAccounts = new String[usernames.length];
} catch (IOException e) {
e.printStackTrace();
}
}
And this method keeps returning 0... regardless of whether or not my file has data in it.
static int countLines() throws IOException {
BufferedReader Kerouac = new BufferedReader(Max);
int lines = 0;
while(Kerouac.readLine() != null)
lines++;
Kerouac.close();
System.out.println(lines);
return lines;
}
After I run the program, unless I call a method that writes to the file, all the contents of the file will be gone.

if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Redundant. Remove.
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
This always creates a new file, which is why the previous line is redundant. If you want to append to the file when it already exists:
Vonnegut = new PrintWriter(new FileOutputStream("src/BankAccounts.txt", true),"UTF-8");
The true parameter tells the FileOutputStream to append to the file.
See the Javadoc.
Or use a FileWriter instead of a FileOutputStream, same principle.

When you create a PrintWriter it will always delete the file if it already exists, from the javadoc:
... If the file exists then it will be truncated to zero size ...
(i. e. its content will be deleted)
Instead of using FileReader and PrintWriter you need to use a RandomAccessFile to write and/or read your file in this way:
RandomAccessFile myFile = new RandomAccessFile("/path/to/my/file", "rw");
In this way the file is automatically created if it doesn't exist, and if it does, it just opens it.

Related

reading in csv file and storing in arrays

the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks
You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}

File isn't written to after program runs

So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().

Java - How to Clear a text file without deleting it?

I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}

Need a Java program that writes all changes made to a txt file into a log.txt file

I know about the new WatchDir feature, but I want the changes made in the FILE and not Directory to be written into a log file. Any changes made to it are written directly into log.txt file. The current code I have: http://pastebin.com/GwURfRbi , writes only the last line into txt file because it is reading only one line.
I need to tweak it in such a way that it reads a line, if changes is made writes into file,
then again keeps reading, and as soon as any change is made, it is written in the txt file instantly. Can anyone help?
code:
import java.io.*;
public class LogMonitor {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("D:/test.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {
String line = br.readLine();
if (line == null) {
Thread.sleep(1*1000);
} else {
byte[] y = line.getBytes();
File g = new File("D:/abc.txt");
OutputStream f = new FileOutputStream(g);
f.write( y );
}
}
}
}
I think your problem is that you did not set the append boolean to true in your OutputStream. Try this:
OutputStream f = new FileOutputStream(g, true);
so that it appends the line instead of overwriting the whole file.

Trying to write to a .DAT file but doesn't seem to be doing anything?

I used this code in a different application to write a name and highscore onto the file for my game. Now i'm using this code to get a name and password from a .DAT file and be able to add a new user and password. Here's the .DAT file.
michael123
speaker123
katherine123
motor123
username
password
Here's the code. Reading the file works fine but writing to it does nothing at all and i'm unsure why.
InputStream file;
BufferedReader fileStream;
FileWriter fileWriter;
BufferedWriter fileWrite;
String temp = "";
int users = 0;
public void readUserInfo() throws IOException {
try {
file = Board.class.getResourceAsStream("users.DAT");
fileStream = new BufferedReader(new InputStreamReader(file));
} catch (Exception e) {
System.out.println("File not found");
}
for (int i = 0; i < users; i++) {
temp = fileStream.readLine();
Board.username[i] = temp.trim();
temp = fileStream.readLine();
Board.password[i] = temp.trim();
}
//Close
fileStream.close();
file.close();
}
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile(),true);
fileWrite = new BufferedWriter(fileWriter);
System.out.println("Users : " + users);
//Skip already created users
for (int i = 0; i < users; i++) {
fileWrite.newLine();
fileWrite.append(Board.username[i]);
fileWrite.newLine();
fileWrite.append(Board.password[i]);
}
System.out.println("Adding" + Board.username[users] + " : " + Board.password[users]);
//Add user
fileWrite.newLine();
fileWrite.append(Board.username[users]);
fileWrite.newLine();
fileWrite.append(Board.password[users]);
//Close
fileWrite.close();
System.out.println("Closed fileWrite");
}
I'm using netbeans. The file being read from is in the same package as all the other classes.
Maybe you have packaged your jar with some state of the file users.DAT (a defined set of users) and when you read them from classpath you see only the users from the time you have created the jar. The writing goes then to another file.
You should read the user from the filesystem too.
Check the working directory of your app there should be correct file containing the users added.
Also no need for copying all the user over and over again every time you add one, just open your file in append mode
fileWriter = new FileWriter(new File("users.DAT"), true);
Unless you want to be able to delete users, in that case keep everything in memory and save when you exit the program or explicitly with a save action.
In your reading you use file = Board.class.getResourceAsStream("users.DAT"); in your writing you just create a file new File("users.DAT") what about changing your addUser() to
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile());
....
}
Edit: The problem is that during writing you are not retrieving the same file as before. I would add this method
public File getUserDataFile() {
return new File(Board.class.getResource("").getFile(), "users.DATA");
}
// then use it like this
new FileWriter(getUserDataFile());
// and
new BufferedReader(new InputStreamReader(getUserDataFile()));
then access it whenever you want to read and write to your file. The problem is Board.class.getResourceAsStream("users.DAT") will return null if your file doesnt exist.

Categories

Resources