util.Properties bug corrupting .properties file on win10 - java

This bug is happening only in win10. Currently in win7 it does not happen.
Essentially I write some text that the user has inputted in various fields.
I use this to save all the info the user wrote, so when the application is relaunched the info is already there.
Also, I call this class every time the user clicks a button.
With normal behavior, the application runs fine on win7, and it saves everything properly. With win10 though, saving effectively "corrupts" the file, or at least, it makes it empty.
package whatever;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class SaveFile {
public static void mainSave(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
String instaPathCombined = "config.properties";
output = new FileOutputStream(instaPathCombined);
// set the properties value, the get methods all retrieve a string.
prop.setProperty("a", UI.geta());
prop.setProperty("b", UI.getb());
prop.setProperty("c", UI.getc());
prop.setProperty("d", UI.getd());
prop.setProperty("e", UI.gete());
prop.setProperty("f", UI.getf());
prop.setProperty("g", UI.getg());
prop.setProperty("h", UI.geth());
prop.setProperty("i", UI.geti());
prop.setProperty("j", UI.getj());
prop.setProperty("k", UI.getk());
prop.setProperty("l", UI.getl());
prop.setProperty("m", UI.getm());
prop.setProperty("n", UI.getn());
prop.setProperty("o", UI.geto());
prop.setProperty("p", UI.getp());
prop.setProperty("q", UI.getq());
prop.setProperty("r", UI.getr());
prop.setProperty("s", UI.gets());
prop.setProperty("t", UI.gett());
prop.setProperty("u", UI.getu());
prop.setProperty("v", UI.getv());
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I have no idea on why it does this.
Also, this is literally a win10 issue, no other factors matter here, as I tried it on a VM with a fresh win10 installation and it happened.

Related

I can't run a python script from java and I think it's because the script does not have execute permissions

I'm trying to run a python script whenever a button on my gui (swing) is pressed. However, the script never runs and I'm not sure how to fix this. I know the script works fine independently, it should be py not python because windows, and my file system ntfs.
So far I've been trying to use code that can be summarized as below:
myBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("py myScript.py");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
I don't think I can chmod ntfs stuff but I tried setting permissions via right clicking the python file and trying to mess with the security settings. Full control for the script to users does nothing.
The python script has the following permissions, my guess is my code isn't working because it does not have execute permissions.
-rw-r--r--
Use complete python executable path instead of "py". It executes the file with just read permissions.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
String cmdOutput = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((cmdOutput = stdInput.readLine()) != null) {
System.out.println(cmdOutput);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
myScript.py
print("This line will be printed.")
Output:
C:\Users\Administrator\Documents\demo>javac Sample.java
C:\Users\Administrator\Documents\demo>java Sample
This line will be printed.

Java, seemingly randomly, started crashing on FileHandle.class.getResourceAsStream(path);

So, I'm working on a program that allows you to import animations in the form of JSON files into Minecraft, and, when working on a completely different part of the program, my import code stopped working.
I'm using eclipse, and this is how my import code looks:
package com.github.sam54123.mc_animation.utils;
import java.io.InputStream;
public class FileHandle
{
public static InputStream inputStreamFromFile(String path)
{
try
{
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
return inputStream;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
new file
package com.github.sam54123.mc_animation.utils;
import java.io.File;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONObject;
public class JSONUtils
{
public static String getJSONStringFromFile(String path)
{
// Open file
Scanner scanner;
try
{
InputStream in = FileHandle.inputStreamFromFile(path);
scanner = new Scanner(in);
// Get JSON as string without spaces or newlines
String json = scanner.useDelimiter("\\Z").next();
// Close file
scanner.close();
return json;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
public static JSONObject getJSONObjectFromFile(String path)
{
File file = new File(path);
if (!file.exists())
{
System.out.println("Invalid Path");
return null;
}
String string = getJSONStringFromFile(path);
return new JSONObject(string);
}
}
And I proceed to do some more fancy pampering of the file later on. This used to work reliably, until I made this in a completely different and un-related class:
String command = getCommand(object);
if (command != null && command.length() > 0)
{
commands.add(new AnimCommand(command, i));
}
And then it started throwing this error:
[Ljava.lang.StackTraceElement;#7852e922
Exception in thread "main" java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.github.sam54123.mc_animation.utils.JSONUtils.getJSONObjectFromFile(JSONUtils.java:47)
at com.github.sam54123.mc_animation.system.Animation.<init>(Animation.java:20)
at com.github.sam54123.mc_animation.testing.Tester.main(Tester.java:13)
I've double checked that the file hasn't changed, and I tried deleting that section of code, restarting Eclipse, the whole deal, and nothing seems to fix it. The code is even able to recognize that the file is valid using the File class, but nothing seems to change. Does anyone have some insight on how this might be fixed? Here is the rest of my code: https://github.com/Sam54123/mc-animation/
EDIT
Okay, I've just done some more debugging, and it looks like it's the
return new JSONObject(string);
on line 47 of the second file that's crashing. No idea why, as the risky stuff of reading a file off disk is okay.
EDIT 2
It looks looks like it's failing because
InputStream in = FileHandle.inputStreamFromFile(path);
is returning null, which makes sense because of the try catch statement
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
is in. Why that's failing beats me though, because the validity of the file is verified elsewhere in the code. It also used to work, and I haven't changed anything about the layout of the files.
EDIT 3
Interesting, a couple System.out.printlns reveal the catch is not actually getting activated, and therefore getResourceAsStream() must actually be returning null. I've confirmed this by printing it out before I return it.

Java Properties: loading null from a .txt file

so I'm currently working on reading information from a text file from the first time, and from what I have pieced together, the following code should work and return 100 and 16:
package Utility;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class textReader {
public textReader()
{}
public Object fetchElement(String fileName, String keyName)
{
Properties properties = new Properties();
try {
properties.load(new FileInputStream("P:/Real_Time_Survival/Real_Time_Survivial_Game/assets" + fileName));
} catch (IOException e) {
}
return properties.getProperty("keyName");
}
}
but when called from the main class with
textReader ready = new textReader();
ready.fetchElement("Sprites/ExampleSprite/Default/SpriteData.txt", "FrameDuration");
ready.fetchElement("Sprites/ExampleSprite/Default/SpriteData.txt", "AnimationFrames");
It returns null (have the system printing out those lines, cut it out due to formatting errors). Any idea as to why this won't work?
I'm going to stick my neck out and guess you left off a "/" after "assets"
I um, put the keyName variable as a string.
Yep this is solved, 10/10 best dumb mistakes ever

Eclipse IDE java equivalent of PHP include?

I've been digging around but can't find anything useful.
I'm working on an Android App.
Basically I have a package and there are three java files in it so far; my main screen page, a settings page and what I have called my 'subs.java' where I am putting useful functions, routines.
What I am trying to do is create this 'subs.java' file where routines that get used in more than one place can be stored.
So I have my main app page and I have a settings page. Both of these 'pages' need to use these common functions.
So I was going to put them in my 'subs.java' so I don't end up doubling up code.
Where I am stuck is now I have this subs.java file how do I link to it ?
In PHP if I want to use another file I just include it and I have access to all it's functions.
I suppose I am trying to build up a library, but Java is new to me.
How then would I do this in Eclipse/Java please ?
Here's my subs file, with some useful functions that I found else where :
package com.example.helloandroid;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class Subs extends Activity {
// Read settings
public String ReadSettings(Context context){
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("settings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
// Save settings
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("settings.dat",MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
The closest thing to PHP's include in Java is import. Read more about using import and package in Java.
If you've created a project as a package then any class using that package can access any other ones. So if you had SomeFileA.java and it uses package com.something.me, and SomeFileB.java that uses package com.something.me then they can reference each other. Typically Eclipse will auto-add any imports if you just flat out write SomeFileB b = new SomeFileB(); inside SomeFileA. If not you can just do use
import com.something.me.SomeFileB;
You would use the import statement to import your subs class. Then you can refer to any function in the subs class as subs.functionName()
If subs.java is in the same folder as your other java files, you can simply type import subs.
Read more about packages and imports at http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html
What about "import" ? You can import a simple class, not only a library...
Put your common routines as static methods in a class ("MyAppHelper" for example), and call them in your "screens" :
MyAppHelper.function1(...)

FTPClient (commons net) Upload problem

I use the following piece of code to upload a photo to a ftp host. But the photo seems to be corrupted after being uploaded:
There are narrow gray lines at the bottom of the photo.
The size of gray lines could be decreased by decreasing the Buffer Size of the FTPClient object.
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import sun.misc.Cleaner;
public class FtpConnectDemo1 {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("ftp.ftpsite.com");
//
// When login success the login method returns true.
//
boolean login = client.login("user#ftpsite.com", "pass");
if (login) {
System.out.println("Login success...");
int replay = client.getReplyCode();
if (FTPReply.isPositiveCompletion(replay)) {
File file = new File("C:\\Users\\e.behravesh\\Pictures\\me2_rect.jpg");
FileInputStream input = new FileInputStream(file);
client.setFileType(FTP.BINARY_FILE_TYPE);
if (!client.storeFile(file.getName(), input)) {
System.out.println("upload failed!");
}
input.close();
}
//
// When logout success the logout method returns true.
//
boolean logout = client.logout();
if (logout) {
System.out.println("Logout from FTP server...");
}
} else {
System.out.println("Login fail...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//
// Closes the connection to the FTP server
//
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this is known error resolved in newest version of library:
http://commons.apache.org/net/changes-report.html#a3.0.1
Never ever heard of corruption of that type, but: are you uploading from behind a firewall? Try doing client.enterLocalPassiveMode(); before calling storeFile.
I've just tried your code on my local computer and it works. I didn't see any gray lines.
So I guess this is either a passive mode thing as Femi suggest or some network/firewall/lower-level problem.
probably late, but it could help somone to avoid waste time.
Check conf file and permitions!! In Unix using vsftp check that
write_enable=YES
stay uncomment.
Check with another FTP client if it posible to upload files.
FTP file sending is not atomic meaning that if there was a crash in the connection only partial file has been send. i would offer add change name to know when transfer is completed in the end of file send.

Categories

Resources