I'm having a little problem with my Java App. I have 2 frames, the mainframe is called MasterFrame. The MasterFrame contains a JList + 3 buttons.
Button 1 can add Block shapes to the JList, this will call the 2nd frame called BlockFrame. Block shapes are Objects stored in the ArrayList shapecollection.
The MasterFrame also contains a Save button which will store objects in a .txt file called "test.txt".
The MasterFrame also contains a Load button which will open the .txt file "test.txt", read the file for objects and set the objects back into the JList. That is what actually is going wrong. The save function works, i'm not quite sure about the load method. It seems that it's actually reading my .txt file for objects but it won't put it back in my Jlist.
The load method might be good, but than there might be a problem with reading the objects and setting them back into the JList. I'm glad if anyone off you guys could give me a hand :)
import java.io.*;
// My File IO Class
public class ShapeIOController {
private String filename;
public ShapeIOController(){
filename= "C:\\Users\\Lars\\Desktop\\test.txt";
}
// The Save method which will save all my created blocks in "test.txt" file
public void save(ShapeCollection shapecollection){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(shapecollection);
out.close();
}
catch( IOException e){
System.out.println("Error occured when trying to open file" + filename);
e.printStackTrace();
}
}
// The open file method which will open "test.txt" file,
// read it's objects and return a ArrayList of shapes "shapecollection"
public ShapeCollection open(ShapeCollection shapecollection){
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
shapecollection= (ShapeCollection) in.readObject();
in.close();
}
catch (ClassNotFoundException e ) {
System.out.println("Unknown class by reading file" + filename);
}
catch ( IOException e ) {
System.out.println("Error occured when trying to open file " + filename);
e.printStackTrace();
}
shapecollection.giveCollection();
return shapecollection;
}
}
// The code for the save button which works
private void SaveShapeButtonActionPerformed(java.awt.event.ActionEvent evt) {
shapeiocontroller.save(shapecontroller.getShapeCollection());
}
// The code where it probably is going wrong
private void LoadShapeButtonActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0; i < shapecontroller.getShapeCollection().giveCollection().size(); i++){
listModel.addElement(shapecontroller.getShapeCollection().giveShape(i).toString());
InfoShapeJList.setModel(listModel);
shapeiocontroller.open(shapecontroller.getShapeCollection());
}
}
// List of methods LoadShapeButtonActionPerformed is using:
// getShapeCollection()
public ShapeCollection getShapeCollection() {
return shapecollection;
}
// giveCollection()
public ArrayList<Shape> giveCollection(){
return shapecollection;
}
// giveShape()
public Shape giveShape(int index){
return shapecollection.get(index);
}
// toString()
public String toString(){
return "Block: " + length + " " + width + " " + height;
}
Related
I want to get one line as header and then rest of data append in the file.but i am facing issue that it is saving the header repeatedly when i have called the function.
Expected output should be like
Id : Title : Group ID
1 : ab : 2
2 : fd : 3
3 : fwsj : 3
public void writeOutputToFile(int id, String title, int groupId) throws IOException {
OutputStream os = new FileOutputStream(new File("output_report.txt"), true);
os.write("\n Id Title Group ID \n ".getBytes());
os.write((id + " " +title + " " + groupId + "\n").getBytes());
os.close();
}
well, inside your method you write the headers to the file, so obviously whenever you call it they'll get written..
You can separate it to two methods- one that writes the headers (and called only once) and another that writes the data (and called once per row).
Alternatively, use some sort of loop inside your method to write each of the lines to the file, after writing the headers once.
The Problem
It is repeatedly putting in the header, because when you call the method, you are always going to insert the header. Instead, you may want to code a util that inputs headers for a file you are creating, and then a separate method for inserting the data.
The Solution
Solution 1)
The helper util method would look something like this:
// String... allows for multiple string parameters to be entered for all of your headers.
public void prepFile(File f, String... headers) {
StringBuffer buffer = new StringBuffer();
for (String header : headers) {
buffer.append(header + "\t");
}
OutputStream os = new FileOutputStream(f, true);
os.write(buffer.toString().getBytes());
os.close();
}
After the file is prepped, you can then use your writeOutputToFile method for all the data.
Edit
Solution 2)
If you were going to make a stand alone class for this, I would recommend you set it up like so:
import java.io.*;
public class OutputFile {
private File file;
private String[] headers;
private boolean existed;
public OutputFile(File f, String... headers) {
this.file = f;
this.headers = headers;
init();
}
private void init() {
existed = file.exists();
// If the file didn't exist, then you want to create it.
if (!existed) {
try {
file.createNewFile();
// Afterwards, you can then write your headers to it.
if (headers != null) {
writeData(headers);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeData(int id, String title, int groupId) {
writeData("" + id, title, "" + groupId);
}
public void writeData(String... strings) {
StringBuffer buffer = new StringBuffer();
for (String s : strings) {
buffer.append(s + "\t");
}
buffer.append("\n");
writeData(buffer.toString());
}
public void writeData(String data) {
OutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(data.getBytes());
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I'm writing a program in order to keep track of DVDs in my library. I'm having trouble altering the text file that saves an added or removed DVD object from the arraylist. Whenever I call my save method, which is the one that overwrites the existing text file holding all the information, it will not change it whatsoever. My add and remove methods work fine but it's just the save method which overwrites the file that I'm reading from that will not work. The following code is what I was attempting to use to save the arraylist to the file. My filename is DVDCollection.txt and the boolean variable flag is a static variable used to check whether or not the code which adds or removes an object from the arraylist was reached.
public void save() {
try{
if(flag=true){
FileWriter instream = new FileWriter("DVDCollection.txt",false);
instream.close();
}else{
return;
}
}catch(IOException e){
System.out.println("The file could not be written to!");
}
}
If you are using java 8 or above it's as simple as:
List<String> lines = Arrays.asList("first line", "second line");
try {
Files.write(Paths.get("my-file.txt"), lines);
} catch (IOException e) {
//handle exception
}
Make sure you provide the right path!
Not sure, why this method should save an array list, as the actual code that writes to this file is missing. Here is simple test, let's start here:
import java.io.*;
import java.util.*;
public class FileSaveTest {
public static void main(String[] args) {
FileSaveTest test = new FileSaveTest();
test.fill();
test.save();
}
public void fill() {
arrayList.add("My disc 1");
arrayList.add("My disc 2");
arrayList.add("Another disc");
}
public void save() {
try {
if(flag) { // you dont need ==true
FileWriter instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
instream.close();
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
}
private ArrayList<String> arrayList = new ArrayList<>();
private static boolean flag = true;
}
Next, it's not very good, to close the file in such manner. If an exception occurs while writing, the file will not be closed. instream.close() should be put into the "finally" block. This block will be executed in any case, regardless of whether an exception occurred or the return keyword met:
public void save() {
Writer instream = null;
try {
if(flag) { // you dont need ==true
instream = new FileWriter("DVDCollection.txt",false);
for (String entry : arrayList) {
instream.write(entry + "\n");
}
} else {
return;
}
} catch(IOException e) {
System.out.println("The file could not be written to!");
} finally {
try {
if (instream != null)
instream.close();
} catch (IOException e) {
System.err.println("Exception during close");
}
}
}
Or, if you are using java 7, you can use try-with-resources syntax:
public void save() {
if(flag) { // you dont need ==true
try (Writer instream = new FileWriter("DVDCollection.txt",false)) {
for (String entry : arrayList)
instream.write(entry + "\n");
} catch(IOException e) {
System.out.println("The file could not be written to!");
}
} // you dont need "return else { return; }" anymore
}
I have a strange bug when executing my code. The first time I save the level, the code properly writes to the file. Upon running the game, the level is properly loaded. However, the second time I try saving on a level that was previously loaded, the save file's arraylists become null. The code DOES NOT throw an error, I noticed only the ArrayList filled with entities, not the level itself, became null, hence does not properly load the game the second time around.
Here is my code:
public void save() {
try (ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(fileName, false))) {
out.writeObject(object);
} catch (IOException e) {
System.out.println("There was a problem saving " + object);
System.out.println(e.getMessage());
}
}
public Object load() {
try (ObjectInputStream in = new ObjectInputStream(
new FileInputStream(fileName))) {
return in.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("There was a problem loading " + object);
System.out.println(e.getMessage());
}
return null;
}
The following methods are called when expected:
public static void saveGame() {
level.save();
System.out.println("SAVED");
System.out.println(level.load());
}
public static void load() {
if (level.load() != null) {
Level.level1 = (Level) level.load();
System.out.println(Level.level1);
System.out.println("LOADED");
}
}
The levels themselves are static, I'm not sure if that has any special rules. Here is the snippet of the Level instance data if that is needed:
protected List<Mob> mobs = new CopyOnWriteArrayList<Mob>();
protected List<Player> players = new CopyOnWriteArrayList<Player>();
private String imagePath;
private transient BufferedImage image;
public static Level level1 = new LordHillsboroughsDomain();
I have a feeling it has something to do with a new instance of the level overwriting the saved level, but I just can't seem to figure it out. Any help is greatly appreciated!
Hello I'm having a little bit of a problem with my text editor like program. I would like to have my Save feature work only if Save As has been called, and if Save is called that it appends the text From a JTextArea to the file created by Save As. I am using ActionListeners from JMenuItems to call the Save and Save As Actions. Here's the code for Save As:
FileDialog fileDialogSave = new FileDialog(frame, "Save", FileDialog.SAVE);
fileDialogSave.setVisible(true);
String userProjectSavePath = fileDialogSave.getDirectory() + fileDialogSave.getFile();
File userProjectSave = new File(userProjectSavePath);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(userProjectSave, true)))) {
userProjectSave.createNewFile();
String userProjectNameToSave = codeArea.getText();
out.println(userProjectNameToSave);
} catch (IOException e1) {
e1.printStackTrace();
}
Both the Save and Save As are nested inside static class ActionSaveAs implements ActionListener { public void actionPerformed(ActionEvent e) { ... } }
The problem is I can't access the String userProjectSavePath in the Save class so I can't append the new text to the same file as in the Save As.
Instead, let your notional saveDocument() method invoke saveDocumentAs() if currentFile is null. The following outline suggests the approach taken in Charles Bell's HTMLDocumentEditor, cited here.
public void saveDocument() {
if (currentFile != null) {
// Save in currentFile
} else {
saveDocumentAs();
}
}
public void saveDocumentAs() {
// Check before overwriting existing file
}
Alright, so I am writing a Java application to import a csv file and then loop through the results, and load them into an array. I am importing the file correctly because it doesn't through an Exception. My issues is that when I try to count the number of records in the FileInputStream I am trapped in an infinite loop. What could be the issue here. Heres the code:
This is my class with a Main method which calls go():
public void go() {
pop = new PopularNames();
popGui = new PopularNamesGui();
String file = popGui.userInput("Enter the correct name of a file:");
pop.setInputStream(file);
pop.getNumberOfNames();
}
This is the class PopularNames (pop), and in the below method I am setting the inputStream var to a new FileINputStream. The file name is provided by the user.
public void setInputStream(String aInputStream) {
try {
inputStream = new Scanner(new FileInputStream(aInputStream));
} catch (FileNotFoundException e) {
System.out.println("The file was not found.");
System.exit(0);
}
}
This is the trouble method. Where I am simply looping through the FileInputStream and counting the number of records:
public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
fileDataRows++;
}
}
public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
inputStream.nextLine(); // Need to read it so that we can go to next line if any
fileDataRows++;
}
}