Java (Mac OS) : Writing my object to a file results in garbled test when re-reading the object from the file - eclipse

I have written the following code using the Eclipse IDE.
When I open the txt file with gb18030,it is some of the test is garbled, as can be seen here:
Any suggestions on how to handle this issue?

Of course, because you are using ObjectOutputStream, try
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("path", false), StandardCharsets.UTF_8);
Check out the answer at Serialzed Objects Stored in File are not readable
and JavaDoc

Related

Writing string to specific dir using chaquopy 4.0.0

I am trying a proof of concept here:
Using Chaquopy 4.0.0 (I use python 2.7.15), I am trying to write a string to file in a specific folder (getFilesDir()) using Python, then reading in via Android.
To check whether the file was written, I am checking for the file's length (see code below).
I am expecting to get any length latger than 0 (to verify that the file indeed has been written to the specific location), but I keep getting 0.
Any help would be greatly appreciated!!
main.py:
import os.path
save_path = "/data/user/0/$packageName/files/"
name_of_file = raw_input("test")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = raw_input("testAsWell")
file1.write(toFile)
file1.close()
OnCreate:
if (! Python.isStarted()) {
Python.start(new AndroidPlatform(this));
File file = new File(getFilesDir(), "test.txt");
Log.e("TEST", String.valueOf(file.length()));
}```
It's not clear whether you've based your app on the console example, so I'll give an answer for both cases.
If you have based your app on the console example, then the code in onCreate will run before the code in main.py, and the file won't exist the first time you start the activity. It should exist the second time: if it still doesn't, try using the Android Studio file explorer to see what's in the files directory.
If you haven't based your app on the console example, then you'll need to execute main.py manually, like this:
Python.getInstance().getModule("main");
Also, without the input UI which the console example provides, you won't be able to read anything from stdin. So you'll need to do one of the following:
Base your app on the console example; or
Replace the raw_input calls with a hard-coded file name and content; or
Create a normal Android UI with a text box or something, and get input from the user that way.

How to get the extension file of Input Stream

I have a code
var test = Base64.getDecoder.decode(base64);
ByteArrayInputStream(test);
var input_stream = new ByteArrayInputStream(test);
Logger.debug(test.getClass.getSimpleName)
How do I get the file extension of the variable input_stream?
I believe you are asking how to determine the image file format from its bytes.
This has already been answered here: Java get image extension/type using BufferedImage from URL
I would not use the term "file extension" to refer to the file format -- while many systems (including Windows) conventionally use the file name extension to indicate the file format, you cannot always rely on this convention, and these are two separate concepts. I found the above question by Googling "java how to detect image type"
Good luck!

MappedByteBuffer Scala/Java

I'm using a MappedByteBuffer in Scala (although this question is relevant to Java too) to open a file of roughly 400MB. Here's a code snippet:
val file = new java.io.File( ... )
val stream = new java.io.FileInputStream( file )
val buffer = stream.getChannel.map(java.nio.channels.FileChannel.MapMode.READ_ONLY, 0, file.length )
However, this fails, with the following error:
java.io.IOException: Channel not open for writing - cannot extend file to required size
From what I've read, you should be able to map a file of up to 2GB. In terms of my JVM settings, I've got -Xmx4G set, so I can't see why it's unable to open the file. By way of a test, I mapped a smaller section of the file (~1mb), which worked correctly.
Does anyone have any ideas?
I'd misread the example I'd seen online, assuming that the third argument to map was the byte of the file to stop reading, whereas actually it is the number of bytes to read. Changing this solves the problem.

Debugging a compiled Groovy script in Eclipse

I'm trying to debug a Groovy script in Eclipse from a JUnit test. The Groovy code is part of a larger Java application that runs in Tomcat. For various reasons our system is set up to use compiled JSR223 expressions. Here's the abbreviated code snippet:
GroovyScriptEngineImpl engine = new GroovyScriptEngineImpl();
Resource r =
new ClassPathResource("groovy/transformations/input/Foo.groovy");
String expression = IOUtils.toString(r.getInputStream());
CompiledScript script = engine.compile(expression);
String result = (String) script.eval(new SimpleBindings(bindings));
The test runs fine, but even though I have a breakpoint set in Foo.groovy, and the file is on the classpath, the breakpoint never gets hit when debugging. I'm guessing this doesn't work because there's no association between the expression in String format and the actual file that contains it. So is there a way of creating this association between the String and its corresponding file name? As mentioned, I need to use a CompiledScript. As a side note, I have been able to hit the breakpoint in the debugger with the same Groovy script when using this approach:
Resource r =
new ClassPathResource("groovy/transformations/input/Foo.groovy");
GroovyShell shell = new GroovyShell(new Binding(bindings));
String str = (String) shell.evaluate(r.getFile());
But of course, in this case the Groovy engine loads the file directly. Any hints as to how to get the first example to work are greatly appreciated. Thanks.
You are exactly right that this has to do with creating a class from a string. GroovyScriptEngineImpl likes to assign arbitrary names to the compiled script since it assumes everything comes from a string. The GroovyShell, however, generates the script name based off of the file that the script comes from, and this is the link that the debugger needs.
I'd perhaps recommend that you avoid using GroovyScriptEngineImpl and use GroovyShell.parse instead. And then, you can create a GroovyCompiledScript from the result of GroovyShell.parse and using a new GroovyScriptEngineImpl. Something like this:
File f = getScriptFile();
Script s = new GroovyShell().parse(f);
CompiledScript cs = new GroovyCompiledScript(new GroovyScriptEngineImpl(), s.getClass());
...
Note that I haven't tried this yet, but based on my experience, this should work.
If you are feeling really good-spirited, I'd raise a jira on the groovy issue tracker to ensure that you can pass in a proper name for scripts created using the GroovyScriptEngineImpl.

What process is Streamreader using?

I made a simple program with
StreamReader sr = new StreamReader(File.OpenRead(dlg.FileName));
txtBox1.Text = sr.ReadToEnd();
and forgot to put
sr.Dispose();
and now when I try to run the program and open a file I get the IOException was unhandled error message that says "The process cannot access the file because it is being used by another process." So my question is, does anyone know what process is it using? I would like to be able to find it in the taskmanager and end it instead of writing a bunch of exception handling code since this is just a program that I'm using for practice.
The file I tried to open is a txt file in MyDocuments.
The process that is using the file is the process that opened it which is very likely .vshost.exe if you are running this from from Visual Studio.
To avoid 'forgetting' to dispose of objects in the future using the using statementfor anything implementing IDisposable (which StreamReader does). Your code would look like
using(StreamReader sr = new StreamReader(File.OpenRead(dlg.FileName)))
{
txtBox1.Text = sr.ReadToEnd();
}
I got the same error when I was using a streamreader to find out the end of the text in the file so I could then add the new text after the text in the file with the writeline method. My Documents has accessibility issues when it come to development anyway. Try putting the .txt into some other location maybe /temp folder?