Java write to the file nonreadable sumbols - java

This is my method, he create new object "predmet". class "AddNewObject" return me predmet type (name, description).
AddNewPredmet addnewpredmet = new AddNewPredmet();
listPredmet.add(AddNewPredmet.AddPredmet());
StorageInFile.savePredmet(listPredmet);
All working. But I have a problem with the result written in the file. The output file has symbols that are not readable as shown -
¬н sr java.util.ArrayListxЃТ™Зaќ I sizexp w sr entity.PredmetїБц)Зя| L Descriptiont Ljava/lang/String;L PNameq ~ xpt testt testx
The following is the function that writes to the file
public class StorageInFile {
static void savePredmet(List<Predmet> listPredmet) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Predmet.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(listPredmet);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Нет такого файла", ex);
} catch (IOException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Не могу записать", ex);
}
}}
How i can fix this? I think about method toString(), but i cant add this method to this code.

Try using a buffered writer and use UTF-8 capable viewer to see the file. You are trying to using a tool that assumes a one-byte encoding, such as the Windows-125x encodings. Notepad is an example of such a tool. So using the capable viewer you can look at it.
Also it would help to show what’s in your file

If you expected to print the contents of every instance of Predmet in the List<> then you could try the following.
Implement to the toString() method in Class Predmet
Try the following snippet to write to file.
FileWriter writer = new FileWriter("sample.txt");
try {
int size = listPredMet.size();
for (int index =0; index < size; index++){
writer.write(listPredMet.get(index).toString());
writer.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
writer.close()
}

Related

How to read binary files in a string sequence of 1 and 0?

I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.
But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.
There is no method like .readString() in DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode contains ready sequence
The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
But I would actually advise you to rewrite you file with some known file format, like so:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
And read it like you would read any other file:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.

Difference between default file paths in pure Java and in Android

I’ve a problem with understanding paths in Android. I’m trying to check if file exists. It works fine in pure Java but fails in Android code and I’m giving the path in the same way (it’s just a file name). I know the file exists (in Android) because I’ve checked it by reading from it before calling to exists() method of File class. I can read the file with no problem but existence check returns false. So my question is: what is the difference between ‘normal’ and ‘android’ Java when it comes to paths?
This problem seems similar to ‘why file.exists() returns false?’ but I’ve done some reading (a lot of it) and didn’t find an answer (to both – how to check if file exists in Android and what’s the difference between paths in pure Java and Java in Android).
Below I’m pasting the code illustrating the case.
This doesn't work in Android:
//--------------------------BUTTONS ACTIONS-----------------------------------------------------
public void onSaveButtonClick(View view){
msg = textInput.getText().toString();
try {
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
fos.write(msg.getBytes());
fos.close();
Toast.makeText(getApplicationContext(), "Zapiasano!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onLoadButtonClick(View view){
loadedMsg = "";
String tmp;
try {
FileInputStream fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuffer stringBuffer = new StringBuffer();
while ((tmp=bufferedReader.readLine()) != null){
loadedMsg += tmp + "\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textDisplay.setText(loadedMsg);
//----------------------FILE CHECK---------------------------------------------
File f = new File(fileName);
if(f.exists()){
textDisplay.setText("File exsists");
} else{
textDisplay.setText("File doesn't exsists");
}
}
And this works in pure Java:
public static void main(String[] args) {
String fileName = "test.file";
String str = "hello kitty!";
String loaded = "this should not load";
//-----------------SAVE------------------------------------------------
try {
FileOutputStream fos;
fos = new FileOutputStream(fileName);
fos.write(str.getBytes());
fos.close();
System.out.println("saved");
} catch (FileNotFoundException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
}
//------------------LOAD -----------------------------------------------
try {
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
loaded = bufferedReader.readLine();
isr.close();
fis.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(loaded);
//----------------------FILE CHECK---------------------------------------------
File file = new File(fileName);
if(file.exists()){
System.out.println("file exsists");
}
}
OUTPUT:
saved
hello kitty!
file exsists
So my question is: what is the difference between ‘normal’ and ‘android’ Java when it comes to paths?
Other Java environments assume a certain current working directory. For all intents and purposes, Android does not.
Your Android code assumes that the following three things are related:
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
FileInputStream fis = openFileInput(fileName);
File f = new File(fileName);
The first two are related. The third is meaningless. The equivalent line would be:
File f = new File(getFilesDir(), fileName);
In Android, you always determine filesystem paths using framework-supplied methods to give you the base directories to work from (getFilesDir(), getExternalFilesDir(), methods on Environment, etc.).
Both the implementation of FileOutputStream(filename) save the file at the location given by the filename. So they kind of assume that its actually the absolute path to file.
The difference is the 'reference' they use to get to that path.
Java on your system sees that path with respect to the source location,
so you use the FileOutputStream(filename) to save file at //filename and then use File(filename) to get that file from /<reference path>/filename and you always find the file therere.
Android's FileOutputStream(filename) sees that location with respect to the files/ directory inside your package directory. While its implementation of File(pathname) see the path with respect to the root directory.
So, in android, when you write using FileOutputStream(filename), you are writing to a file /<path to your package directory>/files/filename, but when you use File(), you actually try to access a file at the root ie /filename, which, do not really exists.
Instead try:
....
File f = new File (YourActivity.this.getFilesDir().getAbsolutePath() + filename);
...

JAVA Warning - Dereferancing Possible Null Pointer. How do I properly get rid of this warning?

I am learning JAVA.
I cannot seem to find a way to get rid of this 'possible null derefence' warning. I have created fOut in the proper scope as null, otherwise I get a 'may not have been initialized' error.
I was unable to find an simple example that would help me fix this. I know it is probably a simple answer.
Thank you.
public static int waveToFile (String filename, byte[] byteWave)
{
FileOutputStream fOut = null;
File file = new File (filename);
try
{
fOut = new FileOutputStream(file);
}
catch (IOException e)
{
}
try{
fOut.write(byteWave); //THIS IS WARNING of POSSIBLE DE-REFERENCE
fOut.close(); //OF NULL POINTER
}
catch (IOException e)
{
}
return mErr;
}
If an exception is thrown fOut can be null. Therefore the compiler is warning you.
To avoid it, check that it is not null:
finally {
if(fOut != null) {
fOut.close();
}
}
As a side note:
do not just swallow exception (catching them doing nothing)
put the close in a finally block to make sure it is executed
do not write in fOut if there has been an exception
You can also use a try-with-resources statement which is perfectly safe and does the work for you:
try(fOut = new FileOutputStream(file)) {
fOut.write(byteWave);
} catch(IOException e) {
// do something with e
}
The fact is that you are constructing the file object and using it in two different try-catch blocks. So if this fails:
fOut = new FileOutputStream(file);
no value will be assigned to fOut, the first catch will handle the exception and the excution will continue with:
fOut.write(byteWave); //THIS IS WARNING of POSSIBLE DE-REFERENCE
fOut.close(); //OF NULL POINTER
Hah! fOut is null because the previous block failed. The warning is well justified.
First of all, wrap the two operations in the same try-catch block:
FileOutputStream fOut = null;
File file = new File (filename);
try {
fOut = new FileOutputStream(file);
fOut.write(byteWave);
fOut.close();
}
catch (IOException e) {
// Do something
}
This piece of code has still a problem: if write fails and an exception is thrown, close
will never be called. You can use a finally block to ensure that the file is closed no matter what or, better, a closing context:
File file = new File (filename);
try (FileOutputStream fOut = new FileOutputStream(file)){
fOut.write(byteWave);
}
catch (IOException e) {
// Do something
}
you need two try block.
public static int waveToFile (String filename, byte[] byteWave)
{
FileOutputStream fOut = null;
File file = new File (filename);
try
{
fOut = new FileOutputStream(file);
fOut.write(byteWave);
if(fOut !=null){
fOut.close();
}
}
catch (IOException e)
{
}
return mErr;
}

Only one object is being saved in a text file using java.io

I started developing an app for my class, which has a request that I need to save objects from a list in a .txt file. It seems to be working, but when I do that, it saves only one object that I entered. I don't know what the solution is. My code is below. P.S. I am using gui to add my objects in a list.
List<Korisnik> listaK=Kontroler.vratiObjekatKontroler().vratiKorisnika();
try {
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
You are closing the output stream once you have written the first object. This way you cannot write anything else into it. Move the out.close() out of for loop.
You are closing your stream inside the for loop. I recommend:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(new File("output.txt"));
out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (out != null) out.close;
if (fos != null) fos.close;
}
Hoping that you are using at least Java SE 7 :) you can take advantage of try-with-resources so you don't need to care about closing "resources":
try (
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos)
){
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
}
The try-with-resources statement contains the FileOutputStream and ObjectOutputStream object declarations that are separated by a semicolon. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the FileOutputStream and ObjectOutputStream objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

Why string didn't write into file?

Function " writeToFile() " will be rapidly called to write string to text file .
but I didn't see any text in the file .
code:
public class MyClass {
private File data_file = new File("data_from_java.txt");
public void writeToFile(String str){
try {
FileOutputStream fos= new FileOutputStream(this.data_file, true);
System.out.print(str); // there is text shown in terminal
fos.write(str.getBytes());
fos.flush();
fos.close(); // why file donesn't have text
}catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
Writing raw bytes may cause problems with character encoding. As Jon Skeet said, use a writer...
try {
FileWriter writer = new FileWriter(data_file, true);
writer.write(str);
} catch(IOException e) {
// oh no!
} finally {
writer.close();
}
Try using this chunk of code:
final BufferedWriter fos = new BufferedWriter(new FileWriter(data_file, true));
System.out.print(str);
fos.write(str);
fos.flush();
fos.close();
It worked for me although i did find my text file in a different place than i expected. Maybe a little searching would do already?
IN ur code fos.write(str.getBytes()); this line causes the problem it seems... write() method takes a byte as an argument.. u r giving array of bytes.. So change that line into
buf = str.getBytes();
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}

Categories