Hello,
I can't find out how to make it so i can save data to a txt. It works while I'm in eclipse but not when i export as a runnable Jar File.
My code is:
public void openFile()
File file = new File(System.getProperty("user.dir"), "src/save/Kube.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x = new BufferedWriter(fw);
}
public void addRecords() {
try {
x.write(game.getTotalCoins() + "\n");
x.write(game.getHighScore() + "\n");
x.write(game.getBackround() + "\n");
x.write(game.getCube() + "\n");
x.write(game.isBlackselected() + "\n");
x.write(game.isBlueselected() + "\n");
x.write(game.isGreenselected() + "\n");
x.write(game.isBlueunlocked() + "\n");
x.write(game.isGreenunlocked() + "\n");
x.write(game.isDefaultselected() + "\n");
x.write(game.isSkyselected() + "\n");
x.write(game.isUnderwaterselected() + "\n");
x.write(game.isSkyunlocked() + "\n");
x.write(game.isUnderwaterunlocked() + "");
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile() {
try {
x.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When ran in eclipse it works fine but when made into runnable jar file does not save.
Thanks for your help!
Related
Im a beginner in coding so please bare with my lack of knowledge, thank you.
i have a code initially looking like this in my catch block
catch (Exception ex)
{
String[] msg = ex.Message.Split(new char[] { '|' });
if (msg[0] == "EXIST")
{
lblStatus.CssClass = "Error";
lblStatus.Text = "<span class='" + Resources.Resource.LangParam2 + "'>" + Resources.Resource.UserNameAlreadyExists + "</span>";
return;
}
else
{
throw ex;
}
}
i am trying to make the code in the catch function into a library function as many code will use it.
for example I am trying smth like this
catch (Exception ex)
{
String[] msg = ex.Message.Split(new char[] { '|' });
Util.GetErrorMessage("SubUser1");
else
{
throw ex;
}
}
and inside my Util.cs code is as below
public static void GetErrorMessage(string acc)
{
if(acc == "SubUser1")
{
String[] msg = new string[] { };
if (msg[0] == "EXIST")
{
string Class = "Error";
string Text = "<span class='" + Resources.Resource.LangParam2 + "'>" + Resources.Resource.UserNameAlreadyExists + "</span>";
return;
}
}
}
any idea that i can make this happen? thank you!
#FXML
void handleButtonAction(ActionEvent event) {
buttonOpenFile.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
openFiletxtField.setText(selectedFile.getAbsolutePath());
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
});
buttonSaveFile.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File file = new File("Details.txt");
try {
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
JOptionPane.showMessageDialog(null, "Saved Successfully..");
osw.flush();
osw.close();
} catch (IOException iOException) {
System.out.println("" + iOException.getMessage());
}
}
});
}
I Have a problem using javafx fxml button click event. Whenever I click the button once, nothing happens. I have to click it the second time for it to work? What could I be doing wrong? I have shared my code above. I am using scene builder I have everything in place apart from this error. everything is working fine apart from this issue. The code load text file from the computer directory and save the data to the loaded file.
#FXML
void handleOpenFileButtonAction(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
openFiletxtField.setText(selectedFile.getAbsolutePath());
}
}
#FXML
void handleSaveFileButtonAction(ActionEvent event) {
File file = new File("Details.txt");
try {
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(firstNametxtField.getText() + "," + lastNametxtField1.getText() + "," + enrolledCheckBox.isSelected() + "," + addresstxtField.getText() + "," + statesCombobox.getSelectionModel().getSelectedItem().toString() + "\n");
JOptionPane.showMessageDialog(null, "Saved Successfully..");
osw.flush();
osw.close();
} catch (IOException iOException) {
System.out.println("" + iOException.getMessage());
}
}
I have a RXTX project that I'm working on. I have it set ups as follows:
public void doConnect(ActionEvent event)
{
String selectedPort = (String)connectTabController.portList.getValue();
System.out.println("Connecting to: " + selectedPort);
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
commPort = selectedPortIdentifier.open("AT QC ReponseTime", TIMEOUT);
serialPort = (SerialPort)commPort;
setConnected(true);
if (isConnected)
{
if (initIOStream() == true)
{
initListener();
System.out.println("Initializing listener");
connectTabController.gui_changeStatusLabel("Device Connected!");
}
}
}
catch (PortInUseException e)
{
System.out.println("Port In use! " + e.toString());
}
catch (Exception e)
{
System.out.println("Failed to open! " + e.toString());
}
}
public boolean initIOStream()
{
//return value for whether opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(RESETTPOD);
System.out.println("Writing Reset command");
successful = true;
System.out.println("IO Stream opened successfully!");
return successful;
}
catch (IOException e) {
System.out.println("I/O Streams failed to open. (" + e.toString() + ")");
return successful;
}
}
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
System.out.println("Too many listeners. (" + e.toString() + ")");
}
}
That's how the connection is made, and it has a listener that's supposed to notify when data is available, which triggers the following:
#Override
public void serialEvent(SerialPortEvent evt) {
BufferedReader reader = null;
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
reader = new BufferedReader(new InputStreamReader(input));
if (reader.ready())
{
fullLine = reader.readLine();
System.out.println(fullLine + "\n");
}
}
catch (Exception e)
{
System.out.println("#SerialEvent Failed to read data. (" + e.toString() + ")");
}
}
}
However, I keep getting "UNDERLYING INPUT STREAM RETURNED ZERO BYTES"
This makes no sense, since if there is nothing to read then the listener shouldnt be triggered int he first place. I tried running the app and I keep getting this error message around every 1/3 second, which corresponds to the burst-output of the device that's sending data. (which works fine in programs like PuttY)
If you are going to use the BufferedReader, take a look at the refence API document for javax.comm, CommPort and getInputStream. Then try using different settings for threshold and receive timeout.
eg).
serialPort.enableReceiveThreshold(3);
serialPort.enableReceiveTimeout(1);
https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/
I have the following method in my UserVerwaltungForm.java:
#FXML
private void clickBtnAdd() {
try {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/AddForm.fxml"));
Scene scene = new Scene(root,400,450);
Stage s = new Stage();
s.setScene(scene);
s.show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here I open a new AddForm and add something there to the database. I do it this way:
#FXML
private void clickBtnAdd() {
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("insert into tbl values (" + PLACEHOLDER_ID + ", '" + tfUsername.getText() + "', '"
+ tfFirstname.getText() + "', '" + tfLastname.getText() + "', '" + tfPassword.getText() + "', '"
+ tfEmail.getText() + "', " + tfBodyWeight.getText() + ", " + tfBodyHeight.getText() + ", "
+ tfActivityPoints.getText() + ", '" + tfBirthdate.getText() + "')");
stmt.execute("commit");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
DBManager.close(stmt);
DBManager.close(con);
Stage stage = (Stage) btnAdd.getScene().getWindow();
stage.close();
}
If I press the button in the AddForm, I want to call this method from the UserVerwaltungForm:
public void loadDataFromDatabase() {
tbl.getItems().removeAll(tbl.getItems());
setCellConfigurations();
try {
con = DBManager.getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select b.* from user_bsd b");
} catch (SQLException e) {
System.err.println("Error at stmt or rs: " + e.getMessage());
}
if (rs != null) {
try {
while (rs.next()) {
factory = new Factory(rs);
u = factory.getUser();
tbl.getItems().add(u);
}
} catch (SQLException e) {
System.err.println("Error at rs.next(): " + e.getMessage());
}
}
DBManager.close(rs);
DBManager.close(stmt);
DBManager.close(con);
}
Do you know, where I should call the loadFromDatabase method in the AddFormController after pressing the button?
I have successfully implemented signalR client for android but my problem is to get return data from server. I can able to send messages from side and it is showing at other client when i am broadcasting but i am not getting the message.
Can anybody help me how to get messages by hubproxy.on method.
String host = "serverlink";
connection = new HubConnection(host);
hub = connection.createHubProxy("myHub");
hub.subscribe(MainActivity.this);
hub.on("addChatMessage", new SubscriptionHandler() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("test");
}
});
// connection.start();
SignalRFuture<Void> awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
}
joinButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
hub.invoke("InformUserName", joinEditText.getText().toString()).get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString()
+ "<<<>>>" + e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString()
+ "<<<>>>" + e.getMessage());
}
}
});
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
hub.invoke("Send", joinEditText.getText().toString(), messEditText.getText().toString()).get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
}
}
});
hub.on is Not Calling how can i initialise subcriptionhandler