Can't write text into .properties file with FileOutputStream on android - java

This is a part of the code I have in my SettingsActivity.java file:
public class SettingsActivity extends Activity {
Thread refresh = new Thread() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Config.writeFile();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (new File(MainActivity.ConfigPath).exists()) {
Config.loadFile();
} else {
Config.writeFile();
}
refresh.start();
}
}
And this is in my Config.java file:
public class Config {
public static void writeFile() {
try {
Properties properties = new Properties();
properties.setProperty("StartOnBoot", String.valueOf(MainActivity.StartOnBoot));
//StartOnBoot is a boolean in the MainActivity.java file
File file = new File("config/app.properties");
file.setWritable(true);
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Favorite Things");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void loadFile() {
try {
Properties properties = new Properties();
FileInputStream fileIn = new FileInputStream(new File("config/app.properties"));
properties.load(fileIn);
MainActivity.StartOnBoot = Boolean.valueOf(properties.getProperty("StartOnBoot"));
fileIn.close();
System.out.println(properties.getProperty("StartOnBoot"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what my Project explorer window looks like
This is what is shown in a logfile from logcat:
07-09 16:16:32.416: W/System.err(621): at
java.io.FileOutputStream.(FileOutputStream.java:94)
And the .properties file still remains empty.
Any ideas how to make it work?
PS:
-API 10
-Target SDK Version 22
-I didn't add any permissions to the AndroidManifest.xml file

For handling properties in Android, use this class:
public class MyPropertiesHolder {
public static int MODE_CREATE = 0;
public static int MODE_UPDATE = 1;
private Context context;
private String filename;
private Properties properties;
public MyPropertiesHolder(Context context, String filename, int mode) throws IOException {
this.context = context;
this.filename = filename;
this.properties = new Properties();
if(mode != MODE_CREATE) {
FileInputStream inputStream = context.openFileInput(filename);
properties.load(inputStream);
inputStream.close();
}
}
public String getProperty(String key){
return (String) properties.get(key);
}
public void setProperty(String key, String value) {
properties.setProperty(key, value);
}
public void commit() throws IOException {
FileOutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
properties.store(outputStream, "");
outputStream.close();
}
}
This is how you use the above class (assuming you are in an Activity):
Creating a new properties file:
MyPropertiesHolder propHolder = new MyPropertiesHolder(this, "test.properties", MyPropertiesHolder.MODE_CREATE);
propHolder.setProperty("test1", "test1");
propHolder.setProperty("test2", "test2");
propHolder.commit();
Updating existing properties file:
MyPropertiesHolder propHolder2 = new MyPropertiesHolder(this, "test.properties", MyPropertiesHolder.MODE_UPDATE);
String test1 = propHolder2.getProperty("test1");
String test2 = propHolder2.getProperty("test2");
propHolder2.setProperty("test3", "test3");
propHolder2.setProperty("test4", "test4");
propHolder2.commit();
Note: You won't see this file in assets directory.

Related

Java: My ArrayList empties itself as soon as I empty the text file from which the ArrayList gets its contents

I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}
Here my SaveGameReader class:
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
And my SaveGameFile class:
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000
What´s the problem with my code?
In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list

Fast zipping folder using java ParallelScatterZipCreator

What should be the value of or initialize InputStreamSupplier?
I was trying to zip all the files in a directory and that should be fast.
So multi threading is the option i'm going for.
public class ScatterSample {
ParallelScatterZipCreator scatterZipCreator = new ParallelScatterZipCreator();
ScatterZipOutputStream dirs = ScatterZipOutputStream.fileBased(File.createTempFile("scatter-dirs", "tmp"));
public ScatterSample() throws IOException {
}
public void addEntry(ZipArchiveEntry zipArchiveEntry, InputStreamSupplier streamSupplier) throws IOException {
if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink())
dirs.addArchiveEntry(ZipArchiveEntryRequest.createZipArchiveEntryRequest(zipArchiveEntry, streamSupplier));
else
scatterZipCreator.addArchiveEntry( zipArchiveEntry, streamSupplier);
}
public void writeTo(ZipArchiveOutputStream zipArchiveOutputStream)
throws IOException, ExecutionException, InterruptedException {
dirs.writeTo(zipArchiveOutputStream);
dirs.close();
scatterZipCreator.writeTo(zipArchiveOutputStream);
}
}
FirstMain Class:
public class FirstMain {
public FirstMain() {
// TODO Auto-generated constructor stub
}
public static void compressFolder(String sourceFolder, String absoluteZipfilepath)
{
try
{
ScatterSample scatterSample=new ScatterSample();
File srcFolder = new File(sourceFolder);
if(srcFolder != null && srcFolder.isDirectory())
{
Iterator<File> i = FileUtils.iterateFiles(srcFolder, new String []{"pdf"}, true);
File zipFile = new File(absoluteZipfilepath);
OutputStream outputStream = new FileOutputStream(zipFile);
ZipArchiveOutputStream zipArchiveOutputStream= new ZipArchiveOutputStream(outputStream);
int srcFolderLength = srcFolder.getAbsolutePath().length() + 1; // +1 to remove the last file separator
while(i.hasNext())
{
File file = i.next();
String relativePath = file.getAbsolutePath().substring(srcFolderLength);
InputStreamSupplier streamSupplier=new InputStreamSupplier(){
#Override
public InputStream get() {
// TODO Auto-generated method stub
return null;
}
};
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(relativePath);
scatterSample.addEntry(zipArchiveEntry, streamSupplier);
}
scatterSample.writeTo(zipArchiveOutputStream);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main( String[] args )
{
compressFolder("C:\\Users\\akatm\\Desktop\\Stuff\\zipdata\\Newtry\\","C:/Users/akatm/Desktop/Stuff/Newtry.zip");
}
}
The get() method must return an InputStream to the file.
You could define an internal class as the following:
static class FileInputStreamSupplier implements InputStreamSupplier {
private Path sourceFile;
FileInputStreamSupplier(Path sourceFile) {
this.sourceFile = sourceFile;
}
#Override
public InputStream get() {
InputStream is = null;
try {
is = Files.newInputStream(sourceFile);
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
That you could then invoke as:
scatterSample.addEntry(zipArchiveEntry, new FileInputStreamSupplier(file.toPath());
You need to set the compress method in the ZipEntry
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(relativePath);
zipArchiveEntry.setMethod(ZipArchiveEntry.STORED);
scatterSample.addEntry(zipArchiveEntry, streamSupplier);
if you don't set the compress method, the method throws an exception.

android load class from jar file

I have written a Java Classloader to load classes from a .jar file.
However when I load a Class I get a ClassNotFoundException. The .jar file is located in folder assets. Before the operation I copied the .jar file in another directory.
Why does it happen and how can I load class from jar file?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
try {
final File dexInternalStoragePath = new File(getDir("lib", Context.MODE_PRIVATE), SECONDARY_DEX_NAME);
(new PrepareDexTask()).execute(dexInternalStoragePath);
if (dexInternalStoragePath.exists()) {
final File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(), null, getClassLoader());
try {
JarFile jarFile = new JarFile(dexInternalStoragePath.getAbsolutePath());
Enumeration<?> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + dexInternalStoragePath.getAbsolutePath() + "!/") };
URLClassLoader cl1 = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
if (className.equals("com.common.lvl.LibraryProvider")) {
LibraryInterface lib = (LibraryInterface) Class.forName(className, true, cl1).newInstance();
//Class<?> libProviderClazz = cl1.loadClass(className);
//LibraryInterface lib = (LibraryInterface) libProviderClazz.newInstance();
lib.CheckLVL(this, "hello");
}
}
// Class<?> libProviderClazz =
// cl.loadClass("com.common.lvl.LibraryProvider");
// LibraryInterface lib = (LibraryInterface)
// libProviderClazz.newInstance();
// lib.CheckLVL(this, "hello");
} catch (Exception ex) {
Logger.Instance().WriteLine(this, ex.getMessage());
}
}
} catch (Exception ex) {
}
}
private boolean prepareDex(File dexInternalStoragePath) {
BufferedInputStream bis = null;
OutputStream dexWriter = null;
try {
bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath));
byte[] buf = new byte[BUF_SIZE];
int len;
while ((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
dexWriter.close();
bis.close();
return true;
} catch (IOException e) {
if (dexWriter != null) {
try {
dexWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return false;
}
}
private class PrepareDexTask extends AsyncTask<File, Void, Boolean> {
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(File... dexInternalStoragePaths) {
prepareDex(dexInternalStoragePaths[0]);
return null;
}
}
Add your jar file, like below
go to -> project properties in eclipse -> java build path -> Libraries -> Add External Jar, And browse and locate you jar file.

How to serve an AbstractResource with an IRequestHandler

I have a form and I want to serve an AbstractResource by calling
getRequestCycle().scheduleRequestHandlerAfterCurrent(target);
Where target has to be an implementation of IRequestHandler.
I want to pass the following AbstractResource object.
public class ExcelResponseResource extends AbstractResource {
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resourceResponse.setTextEncoding("utf-8");
resourceResponse.setFileName("SomeExport.xlsx");
resourceResponse.setWriteCallback(new WriteCallback() {
#Override
public void writeData(Attributes attributes) {
try {
SomeExport export = new SomeExport(arguments);
byte[] byteArray = ((ByteArrayOutputStream)export.getOutputStream()).toByteArray();
attributes.getResponse().write(byteArray);
} catch (Exception e) {
log.error("Something went wrong during Excel generation!", e);
}
}
});
resourceResponse.disableCaching();
return resourceResponse;
}
}
I want to know how i can put this beast into a ResourceStreamRequestHandler or something similar.
Thanks in advance!
Changed the AbstractResource to an AbstractResourceStream and now it works like a charm.
ExcelResourceStream stream = new ExcelResourceStream();
ResourceStreamRequestHandler requestHandler = new ResourceStreamRequestHandler(stream);
getRequestCycle().scheduleRequestHandlerAfterCurrent(requestHandler);
And the ExcelResourceStream looks like this:
public class ExcelResourceStream extends AbstractResourceStream {
private ByteArrayInputStream inputStream;
#Override
public String getContentType() {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
#Override
public Bytes length() {
return Bytes.bytes(inputStream.available());
}
#Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
if (inputStream == null) {
SomeExport export = new SomeExport();
try {
byte[] byteArray = ((ByteArrayOutputStream)export.getOutputStream()).toByteArray();
inputStream = new ByteArrayInputStream(byteArray);
} catch (IOException ioe) {
// STUB
}
}
return inputStream;
}
#Override
public void close() throws IOException {
if (inputStream != null) {
inputStream.close();
}
}
}

Extracting files in .iso using jSevenZip

I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}

Categories

Resources