Why is DataOutputStream in java not working as expected? - java

I am learning about file IO in java, and wanted to test this, but I am not sure why I am getting weird results. Here is the code.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.DataOutputStream;
public class driver {
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("Hello.txt");
DataOutputStream dos = new DataOutputStream(out);
dos.writeBoolean(true);
dos.writeInt(68);
dos.writeChar('c');
dos.writeDouble(3.14);
dos.writeFloat(56.789f);
}
}
My input file "Hello.txt doesn't exist yet and I want to put all these values like 68, c, 3,14 etc into this file, however after running the above program, these are the contents of "Hello.txt".
D c# ¸Që…Bc'ð
So what exactly is happening here?

Related

How do you append to the end of a gzipped file in Java?

Here is what I've tried
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIPCompression {
public static void main(String[] args) throws IOException {
File file = new File("gziptest.zip");
try ( OutputStream os = new GZIPOutputStream(new FileOutputStream(file, true))) {
os.write("test".getBytes());
}
try ( GZIPInputStream inStream = new GZIPInputStream(new FileInputStream(file))) {
while (inStream.available() > 0) {
System.out.print((char) inStream.read());
}
}
}
}
Based on what I've read, this should append "test" to the end of gziptest.zip, but when I run the code, the file doesn't get modified at all. The strange thing is that if I change FileOutputStream(file, true) to FileOutputStream(file, false), the file does get modified, but its original contents are overriden which is of course not what I want.
I am using JDK 14.0.1.
A couple of things here.
Zip and GZip are different.. If you are doing a gzip test, your file should have the extension .gz, not .zip
To properly append "test" to the end of the gzip data, you should first use a GZIPInputStream to read in from the file, then tack "test" onto the uncompressed text, and then send it back out through GZipOutputStream

Function "writeFile(String Text)" Doesn't work the second time used

Before you call this a duplicate, please acknowledge the following facts:
There are no boolean values.
After I read the text files MANUALLY, they were missing the second String supposed to be written to the file.
Here is the code that is supposed to matter:
package StorageBox;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class StorageBox02 {
String FileName;
PrintWriter pw;
Scanner sc;
public StorageBox02(){
}
public StorageBox02(String FileName) {
this.FileName = FileName;
}
public void writeFile(String Text) throws IOException{
FileWriter fw = new FileWriter(FileName);
pw = new PrintWriter (fw);
pw.write(Text + "\t");
pw.close();
}
}
The second string is what is intended to happen when I run the writeFile method twice.
After I read the text files MANUALLY, they were missing the second
String supposed to be written to the file.
Seems like you are trying to append to the previously written file. In that case, you need to open the file in append mode by passing true to the PrintWriter.
For Example, new PrintWriter(fw, true);

Logger is not able to separate data between different files

I made a sort of web scraper in Java that downloads html code and writes it in a logger.
The code for the data miner is the following:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Scraping {
private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public static void getData(String address, int val) throws IOException {
// Make a URL to the web page
URL url = new URL(address);
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
FileHandler fh;
fh = new FileHandler(Integer.toString(val)+".txt");
LOGGER.addHandler(fh);
//SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(new MyFormatter());
LOGGER.setUseParentHandlers(false);
LOGGER.setLevel(Level.FINE);
while ((line = br.readLine()) != null) {
toTable(line);
}
}
/*arrange data in table*/
private static void toTable(String line){
if(line.startsWith("<tr ><th scope=\"row\" class=\"left \" data-append-csv=") && !line.contains("ts_pct")){
LOGGER.log(Level.FINE, line);
}
}
}
When I run the code once it gives me the correct output, but I need to run it multiple times in a for loop (sending another address and index i as val, giving Logger a different name for every iteration), and when I do that, the Logger file appends new data from files that should be in a different file.
So, index 0 gets data for val 0, 1, and 2, instead of having just val 0 data in there.
The file handler boolean append doesn't seem to make any difference for my program's output.
First of all,web scraping isn't data mining. No advanced statistics involved.
Secondly,don't abuse loggers for IO.
Logging is to make sure you get some debug information when your program fails, in a configurable way (so don't use GLOBAL_LOGGER but each class should have a different logger), and you can see what is happening.
For writing your output files, use the standard OutputStream etc. of your programming language. Don't try to reroute your output completely through logging.

Reading Audio file in java

I have written this code for playing audio file,and I want to get indication when my audio file ends after playing. I have tried AS.getMicrosecondLength() == AS.getMicrosecondPosition() but these methods are undefined for the AudioStream.
My Code:
import java.io.FileInputStream;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class A {
public static void main(String arg[]) throws Exception {
AudioStream AS = new AudioStream(new FileInputStream("sounds.wav"));
AudioPlayer.player.start(AS);
}
}
Please tell how I can solve my problem

create multiple files do loop with java and store in a drive , how to?

my first java program ..
so I'm trying to create a file and store in my pc using java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile {
public static void main(String[] args) throws IOException {
int[] numbers = {1,2,3};
for (int item : numbers) {
String key = "file" + item;
File file = File.createTempFile("c:\\",key,".txt");
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
return file;
}
}
what am I missing here .. I coudln't figured it out. everything seem to follow along the book.
Thanks
===========update ===========
after I took of
- return file ;
- throws IOException ;
- and change to File file = File.createTempFile(key,".txt",new File("c:\\"));
I still get this error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
you have some mistakes in java syntax:
When you declare method as void (here public static void main(....)) it means that method has no return value - so line "return file;" not needed here.
Use use wrong signature (wrong parameters types in File.createTempFile function.
Possible usages are:
createTempFile(String prefix, String suffix)
createTempFile(String prefix, String suffix, File directory)
For additional information about File class use this link: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Following possible version of working code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile
{
public static void main(String[] args) throws IOException
{
int[] numbers = {1,2,3};
for (int item : numbers)
{
String key = "file" + item;
File file = File.createTempFile(key,".txt",new File("c:\\"));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
}
}
You can also see another sample how to write text to file: http://www.homeandlearn.co.uk/java/write_to_textfile.html. This link use NetBeans as Java Tool for writing code. I strongly suggest to use some IDE (Eclipse,NetBeans) to write code in java.It will mark your compile mistakes and will suggest corrections.
NetBeans site:https://netbeans.org/
Welcome to Java world
public static void main(String[] args) throws IOException { doesn't return anything, so the return file statement is not required
File.createTempFile either takes String, String, File or String, String so File file = File.createTempFile("c:\\", key, ".txt"); won't compile.
Something like, File file = File.createTempFile(key, ".txt", new File("c:\\")); might be a better idea, but is depended on what you want to achieve.
The JavaDocs state that the prefix must be at least three characters long, so you'll need to pad the key value to meet these requirements.
You MAY find using something like...
File file = new File("C:\\" + key + ".txt");
more managable...

Categories

Resources