Whenever I run my code, the inv.txt file changes from having 25 lines of the character 1 to nothing, could someone tell me what I'm doing wrong?
PS the main class includes inventory.addItem();
public class inventory {
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;
public void addItem(int item, int slot){
int i;
Scanner scan = null;
try {
scan = new Scanner(inventory);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
write = new FileWriter(inventory);
} catch (IOException e) {
e.printStackTrace();
}
for(i = 1; i < slot; i++)writethis.append(scan.nextLine());
System.out.println(writethis.toString());
}
}
Use write = new FileWriter(inventory, true);
It will append data to existing file. See the documentation on FileWriter Constructor for further details.
Related
I am working on a debuging csv output inside an event driven java application. I define my filewriter like this on init.
public File csvFile;
public FileWriter fileWriter;
then I initialies them
this.csvFile = new File("c:\\missingitems.csv");
this.fileWriter = null;
try {
this.fileWriter = new FileWriter(this.csvFile);
StringBuilder line = new StringBuilder();
line.append("Date, ItemId");
line.append("\n");
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
then within my actual program logic this gets called for every timestep in my data
for(Long item : this.items) {
StringBuilder line = new StringBuilder();
line.append(event.getDateTime().toLocalDate().toString() + "," +item.intValue());
line.append("\n");
try {
this.fileWriter.write(line.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
on exit of my program I call
try {
this.fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
However this seems to be only working if i close the filewriter after each append. Is there a way of keeping the file open and just append to it, I would also like to not loose my data in case my application crashes. I am a python guy and not super familiar with java.
I get a resource leak warning in return new ArrayList<>();. The file is not writing in the friends.txt which I am trying to save list in a text file. Please help.
import java.io.*;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
FileOutputStream friendFile;
ObjectOutputStream friendWriter;
try {
friendFile = new FileOutputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendWriter = new ObjectOutputStream(friendFile);
if(friends.size() >0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
friendWriter.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (IOException e) {
System.out.println("Stream cannot be initialized.");
}
}
public ArrayList<Friend> readFriends() {
FileInputStream friendFile;
ObjectInputStream friendReader;
ArrayList<Friend> friends = new ArrayList<>();
try {
friendFile = new FileInputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendReader = new ObjectInputStream(friendFile);
int size = friendReader.readInt();
if(size > 0){
for (int i = 0; i < friendReader.readInt(); i++) {
friends.add((Friend) friendReader.readObject());
}
}
else{
System.out.println("Empty File");
return new ArrayList<>();
}
friendReader.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Stream cannot be inititalized");
}
return friends;
}
}
I am trying to save a list of friends in the friends.txt file. I see no output in the friends.txt file. Is it something to do with my location or FileOutputStream ?
You have two problems in your code.
There is a bug in the for loop in method readFriends of class ReadWrite.
The file friends.txt may not be closed.
Here is the corrected code. Note that I could not find the code for class Friend in your question so I wrote a minimal class. Since you are using serialization, I assume that class Friend implements interface Serializable.
Notes after the code.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
try (OutputStream friendFile = Files.newOutputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectOutputStream friendWriter = new ObjectOutputStream(friendFile)) {
if (friends.size() > 0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be initialized.");
e.printStackTrace();
}
}
public ArrayList<Friend> readFriends() {
ArrayList<Friend> friends = new ArrayList<>();
try (InputStream friendFile = Files.newInputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectInputStream friendReader = new ObjectInputStream(friendFile)) {
int size = friendReader.readInt();
if (size > 0) {
for (int i = 0; i < size; i++) {
friends.add((Friend) friendReader.readObject());
}
}
else {
System.out.println("Empty File");
return new ArrayList<>();
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be inititalized");
e.printStackTrace();
}
return friends;
}
public static void main(String[] args) {
ArrayList<Friend> friends = new ArrayList<>();
Friend friend = new Friend("Jane");
friends.add(friend);
ReadWrite rw = new ReadWrite();
rw.writeFriends(friends);
ArrayList<Friend> newFriends = rw.readFriends();
System.out.println(newFriends);
}
}
class Friend implements Serializable {
private String name;
public Friend(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
In the for loop condition in method readFriends you have the following:
friendReader.readInt()
This means that in every loop iteration, you are trying to read another int from the file friends.txt. This call fails since there is only one int in the file. Hence you need to use size which is the variable that contains the only int in file friends.txt which you read before the for loop.
Since you are using serialization, it is recommended to give the file name an extension of .dat rather than .txt since the file is not a text file.
I always write printStackTrace() in my catch blocks since that helps me to locate the cause of the exception. You actually should not get a FileNotFoundException since Java will create the file if it doesn't exist. If Java fails to create the file, then it is probably because the user has no permission to create a file, so displaying an error message saying to create the file before running your code probably won't help.
Your code may successfully open the file and write some data to it and crash before you have written all the data. In that case, your code does not close the file. If you are using at least Java 7, then you should use try-with-resources to ensure that the files are always closed.
Java 7 also introduced NIO.2 as a better API for interacting with the computer's file system from Java code. I suggest that you use it as I have shown in the code, above.
I'm working on appending objects to a binary file. My professor has provided an "appendable" output stream class for us to use on this assignment, and from my understanding this is what should prevent a corrupted header. However, I'm still getting a corrupted header when I attempt to open the binary file. The name of the file is test.dat and as far as I can tell the program writes the data just fine, but as soon as I try reading from it everything goes out the window.
fileName is a data field in the same class these methods are defined in and is defined as follows File filename = new File("test.dat");
If anyone could point me in the right direction that would be fantastic! Thanks in advance
My Code
/**
Writes a pet record to the file
#param pets The pet record to write
*/
public static void writePets(PetRecord pet){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
/**
Reads all pets from the file so long as the user continues to enter "next"
*/
public static void readPets(){
Scanner keys = new Scanner(System.in);
String input = "";
ObjectInputStream handle = null;
PetRecord pet = null;
try{
handle = new ObjectInputStream(new FileInputStream(fileName)); // stack trace points here
do{
try{
pet = (PetRecord) handle.readObject();
System.out.println("\n" + pet);
System.out.println("[*] type \"next\" to continue");
input = keys.nextLine();
} catch (IOException e){
System.out.println("\t[*] No More Entries [*]");
e.printStackTrace();
break;
}
} while (input.matches("^n|^next"));
handle.close();
} catch (ClassNotFoundException e){
System.out.println("The dat file is currupted!");
} catch (IOException e){
System.out.println("\t[*] No Entries! [*]");
e.printStackTrace();
}
}
Provided class:
public class AppendObjectOutputStream extends ObjectOutputStream
{
// constructor
public AppendObjectOutputStream( OutputStream out ) throws IOException
{
// this constructor just calls the super (parent)
super(out);
}
#Override
protected void writeStreamHeader() throws IOException
{
// this forces Java to clear the previous header, re-write a new header,
// and prevents file corruption
reset();
}
}
Stack Track:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
at UIHandle.readPets(UIHandle.java:381)
at UIHandle.list(UIHandle.java:79)
at UIHandle.command(UIHandle.java:103)
at UIHandle.mainUI(UIHandle.java:40)
at UIHandle.main(UIHandle.java:405)
Turns out it helps if you make sure a file exits before appending to it.
The problem wasn't with reading the file, but attempting to append to a file when it wasn't there. The fix was a simple if/else to check to see if the file existed. If it doesn't exist then write the file as usual, if it does exist then use the custom append class.
/**
Writes a pet record to the file
#param pet The pet record to write
*/
public static void writePet(PetRecord pet){
if (fileName.exists()){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
} else {
ObjectOutputStream handle = null;
try{
handle = new ObjectOutputStream(new FileOutputStream(fileName));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
I'm working on a school project which consist in creating race-tournaments
I'm having an issue right now because I have multiple races-type (CarRace/BikeRace) which have Race as a parent
I'm saving an array of races no matter the specific type.
And now I need to load this list of races
public static ArrayList<Course> loadLRace(String name) {
File inFile = new File(name+".txt");
FileInputStream inFileStream;
ArrayList<Race> lRace = new ArrayList<Race>();
try {
inFileStream = new FileInputStream(inFile);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
int length = inObjectStream.readInt();
for(int i = 0; i < length; i++) {
Race race = (Race)inObjectStream.readObject();
lRace.add(Race);
}
inObjectStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return lRace;
}
And I'm having a "non valid constructor" error, I guess this is because I don't deal with CarRace AND BikeRace separately, but how can I ?
I'm trying to monitor the file content and adding any new line to JTextArea. I created thread, which monitor the file, but when the Scanner object reachs the end of file it stop working. I tried very simple method, which create new Scanner object and read the file from the begin, but it isn't good solution.
It's the version which stop and do nothing :
public class TextAreaThread implements Runnable {
JTextArea text = null;
File file = null;
Scanner read = null;
public TextAreaThread(JTextArea text, File file) {
this.text = text;
this.file = file;
try{
read = new Scanner(file);
}catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null,"Wrong file or file doesn't exist","Error",JOptionPane.ERROR_MESSAGE);
}
}
public void run() {
while(true){
while(read.hasNext())
text.append(read.nextLine()+"\n");
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The wait method is not what you want here. Try Thread.sleep instead.