Android-Writing to a file results in random characters - java

Argargarg.
I am trying to get information from a user input, then to write it to a system file. I get the input, and I call getBytes on it. It logs to the file something along the lines of "null" and random numbers after that. I tried getting it to a string, no luck there, it was a random chain of symbols
Here is the specific code:
TextView note_input=(TextView) findViewById(R.id.note_input);
FileOutputStream fos=null;
String newNote=note_input.getText().toString();
Log.w("Debug",newNote);
try {
fos=openFileOutput("currentNote",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
//IT_SHOUD_NOT_EXIST
}
try {
Log.w("Debug",newNote.getBytes().toString());
fos.write(newNote.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I appreciate any help!

String.getBytes returns array of bytes, and when you try to do toString() you are actually writing it's pointer to string. You already have String change this line
Log.w("Debug",newNote.getBytes().toString());
into
Log.w("Debug",newNote);
and you will have proper Log output, and File should be written properly already.
Hope this helps and enjoy your work

Just a shot in the dark, but I notice you're calling getBytes() without specifying the character encoding. Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output.

Related

How can I plus file's info?

I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.
void save() {
try {
PrintWriter out = new PrintWriter("coins.txt");
out.write(Integer.toString(nmonedas));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void load() {
StringBuffer texto=new StringBuffer();
try {
int c;
#SuppressWarnings("resource")
FileReader entrada=new FileReader("coins.txt");
while((c=entrada.read())!=-1){
texto.append((char)c);
}
}
catch (IOException ex) {}
labelshow.setText(texto.toString());
}
I have this code but i cant plus the info. NEED HELP PLS
Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:
Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
I would put the above in a TRY CATCH block. Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.

Writing into file results in gibberish Java

I'm trying to write some numbers into a *.txt file, using write.write() function. When I open the created file with notepad I see gibberish, but when I open with notepad++, the file is ok. Can anyone explain why is this happening?
try {
for(int i = 0; i < predictionsList.size(); i ++){
writer.write(Integer.toString(predictionsList.get(i)));
writer.write("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The information you provide in the question is not enough, even though we can infer that your issue is related with the encoding of the text file you are writing
Verify the BOM format, that is by default selected in notepad++

Write Hexadecimal Data to File As it is?

I have block of hexadecimal data which i want to write in a file as it is.
Block
000100050000470040002E000000000099009900500000000000490067008D0000000000890081007600000000004C002F0027000000000200050000470040002E0000000000000D00590065006C006C006F00770020006F006C0069007600650000000099009900500000000000000D004F006C006900760065002000790065006C006C006F007700000000490067008D0000000000000D00440069007300740061006E007400200062006C00750065000000008900810076000000000000110050006500610072006C0020006D006F00750073006500200067007200650079000000004C002F00270000000000000F004D00610068006F00670061006E0079002000620072006F0077006E0000
Above block represent a Adobe .aco (stores a color palette) file .
Similar File opened in hex editor shows:-
On trying to write Given block using
Code
try {
File ACO = new File(f.getAbsolutePath(),"NameRandom.aco");
ACO.createNewFile();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ACO)));
try {
writer.write(<-- Above Block -->);
} finally {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
But the above code shows different in hed Editor (as Following image)
I want to write Given block as it is in its current state in file.
You are getting a different hex code because you are writing the string in some encoding. If you wish to write such byte data first convert the data from string to byte[] and then write the bytes.
To convert see: Convert a string representation of a hex dump to a byte array using Java?

How to read a Binary Document from Couchbase - JavaSDK API

I am trying to insert and retrieve small files in couchbase, insertion is successful but when I try to fetch the content and write it to a file am getting below error.
BinaryDocument responsefromDB = bucket.get("KESAVAN", BinaryDocument.class);
try {
FileOutputStream ostream = new FileOutputStream("C:\\Satz\\Test - Copy\\Output.txt");
ostream.write(responsefromDB.content().array());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error :
Exception in thread "main" java.lang.UnsupportedOperationException: direct buffer
at com.couchbase.client.deps.io.netty.buffer.PooledUnsafeDirectByteBuf.array(PooledUnsafeDirectByteBuf.java:363)
at com.couchbase.client.deps.io.netty.buffer.SlicedByteBuf.array(SlicedByteBuf.java:97)
at com.couchbase.client.deps.io.netty.buffer.CompositeByteBuf.array(CompositeByteBuf.java:463)
at com.util.task.CouchbaseClient.main(CouchbaseClient.java:52)
You can only access the array() if hasArray() returns true. Otherwise the Netty buffer itself is backed by native memory. In this case you will need to use one of its getBytes(...) methods to copy the content to an array.
Don't forget to release() the buffer after obtaining it (in the finally block of your try catch for instance).
You seem to be outputing the content into a text file, so is BinaryDocument really what you're after? Maybe StringDocument would be a better, less hurdle, fit? (see http://docs.couchbase.com/developer/java-2.1/documents-basics.html).
Note that if you still have a compelling reason to use BinaryDocument and want the output as a String, you can use ByteBuf.toString(Charset) for this instead of getBytes.

Can't read previously written JSON data (Unterminated String error) in Java

I'm using the twitter4j package for an information retrieval class and have collected some tweets. However, for the next part of the assignment, I am to use Lucene to index on the tweets. In order to do this, my thought was to save the tweets as JSON Strings to a file and then reread them when needed. However, I'm running into an error.
When the file is written, I can see the entire JSON object just fine. The total object is quite large (2500 characters). However, when reading back from the file, I get a Unterminated string at xxxx error. I am using the TwitterObjectFactory methods to both write and read the string. Here is a sample code:
Writing:
public void onStatus(Status status) {
try{
String jsonString = TwitterObjectFactory.getRawJSON(status);
output.write(jsonString+"\n");
numTweets++;
if(numTweets > 10){
synchronized(lock){
lock.notify();
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
Reading:
Scanner input = new Scanner(file);
while(input.hasNext()){
Status status = TwitterObjectFactory.createStatus(input.nextLine());
System.out.println(status.getUser().getScreenName());
}
This works only some of the time. If I run the program multiple times and get many tweets, the program almost always crashes after 2-3 tweets have been read from the file, always with the same error. If you'd like to replicate the code, you can follow this example. I've added a synchronized block in order to close the stream after 10 tweets, but it's not necessary to replicate the error.
Can someone explain what is happening? My guess is that there's something wrong with the way I'm encoding the JSON into the file. I'm using BufferedWriter wrapping an OutputStreamWriter in order to output in UTF-8 format.
Edit: I do close the stream. Here's the bottom snippet of the code:
twitterStream.addListener(listener);
twitterStream.sample("en");
try{
synchronized(lock){
lock.wait();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
twitterStream.clearListeners();
twitterStream.cleanUp();
twitterStream.shutdown();
output.close();
You probably need to flush your output, before you notify the reader. Otherwise parts of your String will stay in the buffer.
public void onStatus(Status status) {
try{
String jsonString = TwitterObjectFactory.getRawJSON(status);
output.write(jsonString+"\n");
output.flush();
numTweets++;
if(numTweets > 10){
synchronized(lock){
lock.notify();
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
I don't see the code where you properly close the BufferedWriter. If you don't close it manually before the first program ends, then data might remain in the internal buffer and never written to the file.
You can also try to open the file in a text editor and look at the contents. Tools like http://codebeautify.org/jsonviewer or http://jsonlint.com/ allow you to validate/beautify the contents to see errors.
Lastly, try BufferedReader( new InputStreamReader( new FileInputStream(file), "UTF-8" ) ). Maybe non-ASCII characters in the input are confusing Scanner.

Categories

Resources