Why does this DataOutputStream print gibberish after my name? - java

everything in the question is in the title.
there's a lot of gibberish after "my name" in the output.
import java.io.*;
public class DOStry {
public static void main(String[] args) {
String file = "file.txt";
String stra = "my name";
int intb = 1;
double douc = 2.5;
char chad = 'f';
try
{
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeUTF(stra);
//i don't know why it prints gibberish after my name.
dos.writeInt(intb);
dos.writeDouble(douc);
dos.writeChar(chad);
dos.flush();
dos.close();
}
catch (IOException e)
{
System.out.println("IOException : " + e);
}
}
}
i'm not good, what have i missed? i'm just trying to learn DataOutputStream.

DataOutputStream is for printing binary, not text and you must read it as a binary file to make sense of it. The fact you can read portions of it as if it were text doesn't mean it is.
I suggest you do the following. These can all be read as text.
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(stra);
pw.println(intb);
pw.println(douc);
pw.println(chad);
dos.close();
In short, if you mix binary and text, you are more likely to get yourself confused.

Related

Using PrintWriter and DataOutputStream to write in same file in java

I have to write both PrintWriter and DataOutputStream to print data onto my file. But PrintWriter is getting printed earlier than DataOutputStream though it comes after DataOutputStream in code.
Part of code:
import java.io.*;
import java.util.*;
public class file {
public static void main(String[] args) {
DataOutputStream dos=null;
PrintWriter pw=null;
try {
File f=new File("file.txt");
dos=new DataOutputStream(new FileOutputStream(f));
pw=new PrintWriter(f);
Scanner b=new Scanner(System.in);
for(int i=0;i<=4;i++) {
int h=b.nextInt();
b.nextLine();
dos.writeInt(h);
String s=b.nextLine();
int l=s.length();
dos.writeBytes(s);
pw.println();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(dos!=null)
try {
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
pw.flush();
}
}
}
new line from pw is getting printed first and then data from dos.write(); how to avoid this?? and make it get in order?
Never mix a Writer and an OutputStream as they are used for different purpose, indeed a Writer is used to generate a text file (readable by a human being) and an OutputStream is used to generate a binary file (not readable by a human being), use only one of them according to your requirements.
Assuming that you decide to use only the DataOutputStream simply replace pw.println() with something like dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII)) to write the line separator into your file with your OutputStream. However please note that in a binary file adding a line separator doesn't really make sense since the file is not meant to be read by a human being.

How to write binary to a file in Java

I am trying to get input from a file, convert the characters to binary and then output the binary to another output file.
I used Integer.toBinaryString() in order to make the conversion.
Everything is working as it should but for some reason nothing is written to the output file, but when I use System.out.println() it outputs fine.
import java.io.*;
public class Binary {
FileReader fRead = null;
FileWriter fWrite = null;
byte[] bFile = null;
String fileIn;
private String binaryString(int bString) {
String binVal = Integer.toBinaryString(bString);
while (binVal.length() < 8) {
binVal = "0" + binVal;
}
return binVal;
}
public void input() throws IOException, UnsupportedEncodingException {
try {
fRead = new FileReader("in.txt");
BufferedReader reader = new BufferedReader(fRead);
fileIn = reader.readLine();
bFile = fileIn.getBytes("UTF-8");
fWrite = new FileWriter("out.txt");
BufferedWriter writer = new BufferedWriter(fWrite);
for (byte b: bFile) {
writer.write(binaryString(b));
System.out.println(binaryString(b));
}
System.out.println("Done.");
} catch (Exception e) {
e.printStackTrace();
}
}
public Binary() {
}
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
Binary b = new Binary();
b.input();
}
}
I know my code is not very good, I'm relatively new to Java so I don't know many others ways to accomplish this.
Use Output stream instead of Writer as writer is not supposed to be used for writing binary content
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(b); // in loop probably

how to set and take in a integer to/from a file in java

So this is a very simple question. I have been trying to research it, and yes I have slightly found some answers but i can't find out how it works so i have come to this.
I am making a simple game in java (pong) and their is a high score integer that i would like to be able save and load from a file (I have heard a lot about using a txt file so probably that, but i have also heard about using a xml i believe is what it is, but i did not look into that as much). How exactly do i program this?
Thank you to all who answer.
PS
I have looked into this code but I don't understand how it's workings
String strFilePath = "C://FileIO//WriteInt.txt";
try {
//create FileOutputStream object
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
dos.close();
} catch (IOException e) {
System.out.println("IOException : " + e);
}
The most simplest way is to create a file, i.e.
write the score to a file, e.g.
String user = "John";
int score = 100;
f = new BufferedWriter(new FileReader(filepath));
f.write(user + "=" + score); // assuming "=" is not inside the user name
f.close();
then read from the file when you need it, e.g.
f = new BufferedReader(new FileReader(filepath));
String line = f.readLine().trim();
String[] temp = line.split("="); // now temp is of the form ["John", "100"]
String user = temp[0];
int score = Integer.parseInt(temp[1]);
f.close();
I think you can solve this encoding the object into a file,but it wont be an xml, it will be a custom file that only your app will be able to open
public void save(Integer ... integersToEncode){
try{
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream (new File(/*yourFileName*/)));
for(Integer encoding : integersToEncode)
output.writeObject(encoding);
output.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
}
For reading
public Integer[] read(int size){
Integer[] objects = new Integer[size];
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream (new File(/*yourFileName*/)));
for(int i = 0; i < size ; i++)
objects[i] = (Integer)input.readObject();
input.close();
}
catch(Exception e){
//What do you want to do if the program could not write the file
}
return objects;
}
Maybe you were confused by the way the original code you posted was printing the char 'd' to the output file. This is the character's ASCII value, as you may know. The following modifications to your code make it work the way you were orginally looking at:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Game {
public static void main(String[] args) throws IOException {
Game game = new Game();
game.writeHighScore();
}
public void writeHighScore() throws IOException{
String strFilePath = "C:/Users/User/workspace/HighScore.txt";
FileInputStream is = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
try
{
//create FileOutputStream object
fos = new FileOutputStream(strFilePath);
dos = new DataOutputStream(fos);
int i = 100;
dos.writeInt(i);
System.out.println("New High Score saved");
dos.close();
// create file input stream
is = new FileInputStream(strFilePath);
// create new data input stream
dis = new DataInputStream(is);
// available stream to be read
while(dis.available()>0)
{
// read four bytes from data input, return int
int k = dis.readInt();
// print int
System.out.print(k+" ");
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
if(dos!=null)
dos.close();
}
}
}

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]);
}

How to output string lines from a file by using recursion and streams in Java

sldls slfjksdl slfjdsl
ldsfj, jsldjf lsdjfk
Those string lines are from a file called "input".
How to ouput those string lines in reverse order to a file called "ouput" by using input, output stream and recursion in Java?
I am not going to put the entire code here but I will put segments from each key areas and hopefully you will figure out to put everything together.
Here is how you should reverse the given string
public static String reverseString(InputStream is) throws IOException {
int length = is.available();
byte[] bytes = new byte[length];
int ch = -1;
while ((ch = is.read()) != -1) {
bytes[--length] = (byte) ch;
}
return new String(bytes);
}
This is how your main method should look like calling the above function.
InputStream is = new FileInputStream(f);
String reversedString = reverseString(is);
And finally hopefully you fill figure out how to write to a file by playing around with this.
try{
// Create file
FileWriter fstream = new FileWriter("/Users/anu/GroupLensResearch/QandA/YahooData/L16/out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(reverseRead(is));
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
This isn't exactly an example of Java best practices, but it works and should be enough to get you started
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException {
Scanner scanner = new Scanner(new File("infile.txt"), "UTF-8");
FileOutputStream fileOutputStream = new FileOutputStream("outfile.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
recurse(scanner, outputStreamWriter);
outputStreamWriter.close();
}
static void recurse(Scanner scanner, OutputStreamWriter outputStreamWriter) throws IOException {
String line = scanner.nextLine();
if (scanner.hasNext())
recurse(scanner, outputStreamWriter);
outputStreamWriter.write(line + "\n");
}
The second encoding argument to Scanner and OutputStreamWriter can be dropped if you're using your system's default encoding.

Categories