I have some problem with saving object to a file. I have class FileManager which contains method that saves object to file. This method is used in class Control which contains main loop (choosing different options). I would like to save object with choosing option EXIt but nothing happens. When I add new option (i.e. 6 - Save database) program works fine. I will be grateful for any clues what can be wrong.
class FileManager {
package utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import data.DataBase;
public class FileManager {
public static final String FILE_NAME = "file.txt";
public void writeDataBaseToFile(DataBase db) {
try (
FileOutputStream fos = new FileOutputStream(FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
) {
oos.writeObject(db);
} catch (FileNotFoundException e) {
System.err.println("Błąd");
} catch (IOException e) {
System.err.println("Błąd");
}
}
}
Control Class :
class Control {
package app;
import data.DataBase;
import data.Expense;
import data.Income;
import utils.AccountInfo;
import utils.AddData;
import utils.FileManager;
import utils.Info;
import utils.Options;
public class Control {
private AccountInfo account;
private AddData addData;
private DataBase dataBase;
private Info inf;
private Income income;
private FileManager fileManager;
public Control() {
addData = new AddData();
dataBase = new DataBase();
inf = new Info(dataBase);
account = new AccountInfo(dataBase);
fileManager = new FileManager();
}
public void ControlLoop() {
Options option;
printOptions();
while((option = Options.createOption(addData.getOption())) != Options.EXIT) {
try {
switch(option) {
case ADD_INCOME:
addIncome();
break;
case ADD_EXPENSE:
addExpense();
break;
case PRINT_INCOME:
printIncome();
break;
case PRINT_EXPENSE:
printExpense();
break;
case RESUME_ACCOUNT:
resumeAccount();
break;
case EXIT:
saveData();
}
} catch(NullPointerException ex) {
}
printOptions();
}
addData.close();
}
public void addIncome() {
income = addData.createIncome();
dataBase.addBudget(income);
}
public void addExpense() {
Expense expense = addData.createExpense();
dataBase.addBudget(expense);
}
public void printIncome() {
inf.printIncome();
}
public void printExpense() {
inf.printExpense();
}
public void resumeAccount() {
account.resumeIncome();
account.resumeExpense();
}
public void saveData() {
fileManager.writeDataBaseToFile(dataBase);
}
public void printOptions() {
System.out.println("Wybierz opcję:");
for(int i=0; i<6; i++) {
System.out.println(Options.values()[i]);
}
}
}
Your code can never reach the EXIT case.
Because when option is EXIT, it terminates the loop.
while ((option=...) != Options.EXIT) {
// execute loop body when option is not EXIT
switch (option) {
...
case Options.EXIT: // <-- it can simply not reach here. not ever.
saveData();
}
Try move saveData() outside the while loop.
while (...) { // process options
}
// We are exiting, save data.
saveData();
addData.close();
P.S. You need to close the output stream in your FileManager.
Related
Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.
I want to display information that I have loaded in from 2 methods onto my TextArea. The methods I am trying to call and display are named loadFleet and loadCrew which are in the Fleet class. I only have it working to where it prints out to the console like so System.out.println(Enterprise). I am pretty new to Java and JavaFX, so any help would be greatly appreciated.
Here's my MainController file:
package application.controller;
import java.io.IOException;
import application.model.Fleet;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class MainController implements EventHandler<ActionEvent>{
#FXML TextField starshipname;
#FXML TextArea shipInfo;
#FXML Button shipEnter;
#Override
public void handle( ActionEvent event) {
/*try {
Fleet.loadFleet(null);
} catch (IOException e) {
shipInfo.setText(" Starship name not found! ");
e.printStackTrace();
}*/
Fleet Enterprise = new Fleet( "Bozeman" );
try {
Enterprise.loadFleet("data/fleet");
Enterprise.loadCrew("data/personnel");
System.out.println(Enterprise);
}catch( IOException e ) {
System.out.println( "Error loading the file - please check its location." );
e.printStackTrace();
}
}
}
And here's my Fleet class:
package application.model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Fleet {
private String fleetName;
public ArrayList<Starship> ship;
private String fileName;
public Fleet( String name ) {
this.fleetName = name;
this.ship = new ArrayList<Starship>();
}
public String getFleetName() {
return this.fleetName;
}
public void setFleetName( String name ) {
this.fleetName = name;
}
public ArrayList<Starship> getStarship() {
return this.ship;
}
public void setStarship( ArrayList<Starship> ship ) {
this.ship = ship;
}
public String getFileName() {
return this.fileName;
}
public void setFileName( String fName ) {
this.fileName = fName;
}
public void addShip(Starship starAdd) {
this.ship.add(starAdd);
}
public void getStarshipsByName( Starship starName ) {
Starship starname;
}
public void loadFleet(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/fleet.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Starship tmp = null;
tmp = new Starship( items[0], items[1], items[2]);
this.addShip(tmp);
}
scan.close();
}catch(IOException e) {
e.printStackTrace();
}
}
public void loadCrew(String fileName)throws IOException {
try {
Scanner scan = new Scanner(new File("data/personnel.csv") );
while( scan.hasNextLine() ) {
String line = scan.nextLine();
String[] items = line.split(",");
Crewmember tmp = null;
tmp = new Crewmember( items[0], items[1], items[2], items[3], items[4]);
for(int i = 0; i < this.ship.size(); ++i) {
if(this.ship.get(i).getStarShipRegistry().equals(items[3]))
this.ship.get(i).addCrew( tmp );
}
}
scan.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public String toString() {
String ret = " ";
for( int i = 0; i < this.ship.size(); i++)
{
ret += this.ship.get(i).toString();
}
return ret;
}
}
Please let me know what other classes or methods you would like for me to provide.
add data to shipInfo (your TextArea) by appending from foreach
loop of your list.
Quick sample code:
//instance of your ship object
StarShip myShip = StarShip();
//method to add data to your TextArea
private void showShipInfo(){
//getStarShip returns the list of ships
//same as the method on your Fleet class
myShip.getStarShip().forEach(starShip ->{
//add data to TextArea for each field of
//StarShip object you want to display
shipInfo.append(starShip.getName());
//shipInfo.append(starShip.get....());
//shipInfo.append(starShip.get....());
}
}
Note: only String values are allowed to be appended to TextArea!
Hope it helps!
I need some help, I'm making a program like a file manager. In my program I need to make simultaneous files copies. For that I use SwingWorker to see the progress of the copies in a JProgressbar, but I need to know how to add more files to Copy in the task with the same destination.
This is my class that extends from Swingworker in my principal program I´ll select some files or folders to copy in one destination. What I need is while the Copytask is working I can to add more files to the Copyitem Arraylist.
Please help and sorry about my english.
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import xray.XRAYView;
public class CopyTask extends SwingWorker<Void, Integer>
{
ArrayList<CopyItem>copia;
private long totalBytes = 0L;
private long copiedBytes = 0L;
JProgressBar progressAll;
JProgressBar progressCurrent;
boolean override=true;
boolean overrideall=false;
public CopyTask(ArrayList<CopyItem>copia,JProgressBar progressAll,JProgressBar progressCurrent)
{
this.copia=copia;
this.progressAll=progressAll;
this.progressCurrent=progressCurrent;
progressAll.setValue(0);
progressCurrent.setValue(0);
totalBytes=retrieveTotalBytes(copia);
}
public void AgregarCopia(ArrayList<CopyItem>addcopia)throws Exception{
copia.addAll(copia.size(), addcopia);
totalBytes=retrieveTotalBytes(addcopia)+totalBytes;
System.out.println("AL AGREGAR: "+copia.size()+" Tamaño"+totalBytes);
}
public File getDriveDest(){
File dest=new File(copia.get(0).getOrigen().getPath().split("\\")[0]);
return dest;
}
#Override
public Void doInBackground() throws Exception
{
for(CopyItem cop:copia){
File ori=cop.getOrigen();
File des=new File(cop.getDestino().getPath());
if(!des.exists()){
des.mkdirs();
}
if(!overrideall){
override =true;
}
File para=new File(cop.getDestino().getPath()+"\\"+ori.getName());
copyFiles(ori, para);
}
return null;
}
#Override
public void process(List<Integer> chunks)
{
for(int i : chunks)
{
progressCurrent.setValue(i);
}
}
#Override
public void done()
{
setProgress(100);
}
private long retrieveTotalBytes(ArrayList<CopyItem>fich)
{
long size=0;
for(CopyItem cop: fich)
{
size += cop.getOrigen().length();
}
return size;
}
private void copyFiles(File sourceFile, File targetFile) throws IOException
{
if(overrideall==false){
if(targetFile.exists() && !targetFile.isDirectory()){
String []options={"Si a Todos","Si","No a Ninguno","No"};
int seleccion=JOptionPane.showOptionDialog(null, "El fichero \n"+targetFile+" \n se encuentra en el equipo, \n¿Desea sobreescribirlo?", "Colisión de ficheros", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, null);
switch(seleccion){
case 0:
override=true;
overrideall=true;
break;
case 1:
override=true;
overrideall=false;
break;
case 2:
override =false;
overrideall=true;
break;
case 3:
override =false;
overrideall=false;
break;
}
}
}
if(override || !targetFile.exists()){
FileInputStream LeeOrigen= new FileInputStream(sourceFile);
OutputStream Salida = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024];
int tamaño;
long fileBytes = sourceFile.length();
long totalBytesCopied = 0;
while ((tamaño = LeeOrigen.read(buffer)) > 0) {
Salida.write(buffer, 0, tamaño);
totalBytesCopied += tamaño;
copiedBytes+= tamaño;
setProgress((int)Math.round(((double)copiedBytes++ / (double)totalBytes) * 100));
int progress = (int)Math.round(((double)totalBytesCopied / (double)fileBytes) * 100);
publish(progress);
}
Salida.close();
LeeOrigen.close();
publish(100);
}
}
}
Here is CopyItem class
import java.io.File;
public class CopyItem {
File origen;
File destino;
String root;
public CopyItem(File origen, File destino) {
this.origen = origen;
this.destino = destino;
}
public CopyItem(File origen, File destino, String root) {
this.origen = origen;
this.destino = destino;
this.root = root;
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public File getOrigen() {
return origen;
}
public void setOrigen(File origen) {
this.origen = origen;
}
public File getDestino() {
return destino;
}
public void setDestino(File destino) {
this.destino = destino;
}
#Override
public String toString() {
return super.toString(); //To change body of generated methods, choose Tools | Templates.
}
}
yes you can add the files directly to source List(the list contains files to be copied ) but you need to synchronize your code because adding more file will be in different thread(UI Thread),another way is to implement (produce/consumer ) using BlockingQueue
Consumer class run in separate Thread or Swingworker coping files is in progress.
Producer class runs UI Thread (selecting more files).
both should have access to BlockingQueue (contains files to be copied)(of course BlockingQueue implementations are thread-safe based on the documentation. ,it has the advantage to block the execution and wait for the files to be added this is very useful if you dont know when the files are added )
I prefer using Thread Pool to manage the threads executions(Optional).
I'm using Netbeans 7.2 on OS X 10.9. The JFileChooser.showSaveDialog() fails on certain occasions. Before I call the showSaveDialog, I call showOpenDialog to open an .srt file. The show dialog fails only when I open certain files esp. from /Volumes/.. on a mounted device. Here's the code:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.io.FilenameUtils;
public class FileSaver extends JFileChooser {
private int result;
private File subFile;
private File save;
private File filename;
private String rectifiedSub;
private FileNameExtensionFilter filter;
public FileSaver(File subFile, String rectifiedSub) {
this.subFile = subFile;
this.rectifiedSub = rectifiedSub;
filename = new File(System.getProperty("user.home"));
filter = new FileNameExtensionFilter("Subtitle Files (*.srt)", "srt");
}
public void createAndShowGUI() {
System.out.println("6");
this.setDialogTitle("Select destination");
System.out.println("6");
this.setCurrentDirectory(filename);
System.out.println("6");
this.setSelectedFile(new File(subFile.getName()));
System.out.println("6");
this.setFileFilter(filter);
System.out.println("6");
result = this.showSaveDialog(this);
System.out.println("6");
if(result == JFileChooser.APPROVE_OPTION) {
save = fixExtension(this.getSelectedFile());
write(save);
}
this.setVisible(true);
}
public void write(File save) {
FileWriter fw = null;
try {
fw = new FileWriter(save);
fw.write(rectifiedSub);
} catch (IOException ex) {
Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fw.close();
} catch (IOException ex) {
Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public File fixExtension(File file) {
if(!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase(".srt"))
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName()).concat(".srt"));
return file;
}
}
Output:
6
6
6
6
6
It stops at the 6 before the line result = this.shhowSaveDialog(this);. The program freezes after that and the save dialog doesn't show up. It works perfectly fine on some files. Somebody tell me whats happening ?
Git: https://github.com/Jimmy-666/Subzero.git
Currently doing a typestate project and I am having problems with importing the List class. When I try to compile the class it throws an error in command line saying cannot find symbol and points to the List symbol. I was wondering how you fix this. It seems to work for String and Integer but not for List.
The java file is automatically create via another program that translates .scr files. In the scr file I use the following line :
type <java> "java.lang.List" from "rt.jar" as List;
Java file:
package demos.Redis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class ClientRole {
private BufferedReader socketServerIn = null;
private PrintWriter socketServerOut = null;
public ClientRole(){
ServerSocket serverServer = null;
try {
serverServer = new ServerSocket(20000);
}
catch(IOException e) {
System.out.println("Unable to listen on ports");
System.exit(+1);
}
Socket socketServer = null;
try {
System.out.println("Accepting...");
socketServer = serverServer.accept();
System.out.println("Server accepted");
}
catch(IOException e) {
System.out.println("Accept failed");
System.exit(+1);
}
try {
socketServerIn = new BufferedReader(new InputStreamReader(socketServer.getInputStream()));
socketServerOut = new PrintWriter(socketServer.getOutputStream(), true);
}
catch(IOException e) {
System.out.println("Read failed");
System.exit(+1);
}
}
public void send_WATCHListToServer(List payload) { HERE IS WHERE IT BREAKS!!
this.socketServerOut.println(payload);
}
public Choice1 send_Choice1LabelToServer(String payload) {
this.socketServerOut.println(payload);
int intLabelChoice1 = Integer.parseInt(payload);
switch(intLabelChoice1){
case 1:
return new Choice1(Choice1.GET);
case 2:
return new Choice1(Choice1.WATCH);
case 3:
default:
return new Choice1(Choice1.MULTI);
}
}
public void send_GETStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public String receive_GET_respStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public void send_MULTIStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public Choice2 send_Choice2LabelToServer(String payload) {
this.socketServerOut.println(payload);
int intLabelChoice2 = Integer.parseInt(payload);
switch(intLabelChoice2){
case 1:
return new Choice2(Choice2.SET);
case 2:
return new Choice2(Choice2.DISCARD);
case 3:
default:
return new Choice2(Choice2.EXEC);
}
}
public void send_SETStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public void send_DISCARDStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public void send_EXECStringToServer(String payload) {
this.socketServerOut.println(payload);
}
public Choice3 receive_Choice3LabelFromServer() {
String stringLabelChoice3 = "";
try {
stringLabelChoice3 = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error, unable to get label");
System.exit(+1);
}
int intLabelChoice3 = Integer.parseInt(stringLabelChoice3);
switch(intLabelChoice3){
case 1:
return new Choice3(Choice3.EXEC_OK);
case 2:
default:
return new Choice3(Choice3.EXEC_FAIL);
}
}
public String receive_EXEC_okStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public String receive_EXEC_failStringFromServer() {
String line = "";
try {
line = this.socketServerIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
}
Command Line
Your Java file is missing an import statement for java.util.List, which is why it's failing to compile.
Unlike String and Integer, List is not in the java.lang package. You need to import java.util.List, not java.lang.List.
If I'm understanding your scenario correctly, your other program is generating the import statements and attempting to add an import for java.lang.List, which doesn't actually exist. Interestingly, there's no import statement in your code for java.lang.List. I don't know if that's a bug in your other program or a feature! But more than likely your problem will go away if you replace your line in the .scr file with type <java> "java.util.List" from "rt.jar" as List;
You are using the interface List but you didn't import it, it says that It can not find symbol java.lang.List because it is trying to search this class in the default java.lang package, add the import java.util.List and you are not going to have problems