Write to file in JAVA

http://download-llnw.oracle.com/javase/6/docs/api/java/io/FileWriter.html

FileWriter is meant for writing streams of characters.

what is the definition of stream?

Please explain about the mechanism Of write files in Java.How buffer and stream relates to each other and work?

If you read the example in this site, It uses byte stream for reading char.

but it is said:

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed in the next section.

1-I want to know advantage of character streams.As you see in the example, Byte stream can read char, Then why it actually represents a kind of low-level I/O that you should avoid

2-
I want to know what happened in behind,

what are the details?What is difference between fileinputstream and filereader streams?What does ObjectOutputStream do that is suitable for read objects?

DataInputStream is an implementation of the abstract class InputStream.

If your file contains primitives, then, yes, a DataInputStream should be used, if it contains characters, on the other hand, FileInputStream should be used, though, FileReader would be easier.

Now, that said, it is possible to have primitive data in character form (uh oh) - here’s the easy way to tell what you’ve got: open the file with notepad.exe, can you (the human) read it? If so, use FileInputStream because the data is stored as characters, if you get gobble-de-gook, it’s in hex and you should use DataInputStream.

A stream is a stream is a stream. (remember the 1s and 0s discussion?..do you even read our responses?)

Thinking about this with ‘real’ objects, a stream is like a copper wire. Copper wire is copper wire, doesn’t matter what we call it. When we hook a copper wire between our video card and our monitor, we might call it an ‘HDMI cable’. Has it changed? Is it somehow different now that we have given it an application specific name? Nope, it’s still just a copper wire.

From what I understand, DataInputStream is used when you want to read primitive Java data types.As int , float,

I read this in JAVA cookbook:

The Stream classes have been in Java since the JDK 1.0 release and are optimal for
reading/writing bytes, rather than characters. The “data” layer over them, comprising
DataInputStream and DataOutputStream, are configured for reading and writing binary
values, including all of Java’s built-in types. Suppose that you want to write a binary integer plus a
binary floating-point value into a file and read it back later. This code shows the writing part:
import java.io.*;
/** Write some data in binary. */
public class WriteBinary {
public static void main(String argv) throws IOException {
int i = 42;
double d = Math.PI;
String FILENAME = “binary.dat”;
DataOutputStream os = new DataOutputStream(
new FileOutputStream(FILENAME));
os.writeInt(i);
os.writeDouble(d);
os.close( );
System.out.println("Wrote " + i + ", " + d + " to file " +
FILENAME);
}
}
The reading part is left as an exercise for the reader. Should you need to write all the fields from
an object, you should probably use an ObjectDataStream; see Section 9.17.

Are you agree with this:

The DataInputStream class is now depreciated but can still be
used by people who have older versions of the JDK.

Will buffer space allocated for a JAVA program after compile?
The buffer be allocated at Runtime.

What is difference between FileInputStream and DataInputStream in this code?
One says File, the other Data, you tell me.

Let’s take it step by step.

In OOP, like in the real life, objects need to interact with each other in order to make them self useful, using streams of data.

What is a real life analogy of these streams?

Let’s take, for example, two people. In order to interact they talk, meaning they exchange data, using streams of words:

  • 
    

What is a pipeline?

Let’s assume that these two people have a chain of command and that they have at least one level between and separating them. Now, for the boss to get the word to the other one, will resort to another person in between. So the boss will stream to the next in chain of command, who, in return will pipe that stream to the next person:

  • 
    

What is a buffer?

Let’s take the jungle stream. If you will need a constant stream, without intreruptions, you can pray to god that this will be true, or you’ll build a dam. The dam is your buffer: it holds enough water to ensure you will always have a constant stream.

Is this any help? :slight_smile: Given your level of detail and curiosity, you should be asking this questions in an assembly language discussion forum (or a low level programming language forum) :slight_smile: Java (and not only, all high level programming languages) offers on abstraction for you not to focus on these these mechanisms, but on programming techniques and alghoritms. Unless you are planning the next Java implementation.

I read it in a tutorial:

Streams attach data to objects. Data flows in streams. An input data stream is needed to connect
data from the keyboard to your program. The connection to the keyboard is System.in. An output
data stream is needed to send data to from your program to the computer screen

Another definition:

A Stream is a file or a physical device (e.g. printer or monitor) which is manipulated with a pointer to the stream.

Does monitor attach data to object?!!!

Dear rushiku,

1-May do a favor and design a figure to describe idea of stream while reading a file?

2- May you tell me a simple definition of stream

Its been a while since I read the replies, but I thought that was already answered.

Characters = “text”
Bytes = “binary”

And yes, text is binary. But what would you rather read … 00100101011 … or “this is text”
and why would you want to change 00100101011 to “this is text” when you can just read it as text straight away?

Yes! I went there! and I come back here with a question in my heart!

May do a favor and give me a real example by code? When do you need to read or write individual bytes.

010010000110010101110010011001010010000001111001011011110111010100100000011001110110111100100001

( Copy above and paste here )

Open up Windows Explorer.
Navigate to where you Java installed.
Find file named src.zip.
Unzip src.zip.
Navigate to java/io
Open various classes you have questions about and read the code.

Now, that said:

What is difference between fileinputstream and filereader streams?

See FileInputStream:19
(the colon means ‘line’)

why it actually represents a kind of low-level I/O that you should avoid

See DataInputStream:11

Sorry, I know its not so easy to grasp, but I can’t think of a better way to say it. (from my earlier reply)

Character streams hide the complexity of dealing with these encodings by providing two classes that serve as bridges between byte streams and character streams.

A second advantage of character streams is that they are potentially much more efficient than byte streams. The implementations of many of Java’s original byte streams are oriented around byte-at-a-time read and write operations. The character-stream classes, in contrast, are oriented around buffer-at-a-time read and write operations.

The ability to reassign these streams corresponds to what Unix (or DOS command line) users
think of as redirection, or piping. This mechanism is commonly used to make a program read
from or write to a file without having to explicitly open it and go through every line of code
changing the read, write, print, etc., calls to refer to a different stream object. The open operation
is performed by the command-line interpreter in Unix or DOS, or by the calling class in Java.

Java cookbook -Orielly

May someone explain about piping?

Sir,Was my imagine about stream and pipeline right?

The interaction of the JVM with the host environment is platform dependent, given that Java (programming) is platform independent, this is well beyond the scope of this forum.

To answer these questions, you’ll need to research your OS’s file handling tech and dig through some low level JVM docs.

You’re over-thinking this rather simple concept.

Consider this:

In the computer world, from the computer’s point of view, there are no letters, no numbers, no symbols and no white space - only 1s and 0s. (truth be told, there aren’t even 1s and 0s, the common idea of binary 1s and 0s is a human invention to represent the position of switches that are either open (0) or closed (1))

Given that, we can say that data ‘travels’ within the computer in continuous ‘streams’ of 1s and 0s.

In order to relieve the tedium of reading binary, we, humans, initially broke the streams of bits into hits (hexadecimal digits). So 0000 becomes 0 and 1111 becomes F.

By combining 2 hits, we get a byte, or 8 bits, which have 2^8 (256) possible values. Which is plenty for most languages.

We then created a standardized character map which is used to translate our language into computer language.

So when you type ‘abalfazl was here’, the computer receives the stream:
hex: 6162616C66617C6C207761732068657265
binary: 01100001011000100110000111000110011001100001011111001101100001000000111011101100001011100110010000001101000011001010111001001100101

If we now play the part of the computer and translate the first byte off of the stream, we get:
01100001
0110 0001
61
a

Interesting, as of Java 6, DataInputStream is not deprecated. So, no, I don’t agree with that.

Yeah, and if you follow the link for pipeline: “Software pipelines, where commands can be written so that the output of one operation is automatically used as the input to the next, following operation. The Unix command pipe is a classic example of this concept; although other operating systems do support pipes as well.”

We see that your quote does nothing but prove that pipelines are nothing more than redirected streams and you’re STILL unclear on the concept.

Please read 396. As it said, We have different streams, inputstream, Datainput streams…

And any kind of streams has its own data.

Then, We want to read a file as we want to readprimitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values, We use Datainputstream, Because it has the datas we need.

For example: You have a program that writes prices to file, You will need to read these data and do a calculation operation on them, Then data Of these file must be read as int data,not char data…

This is the time to use Datainputstream.

In fact Datainputstream wraps inputstream.

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.

http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/io/DataInputStream.html
The "underlying input stream " is inputstream,

Right?

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    [B]FileInputStream fstream = new FileInputStream("textfile.txt");[/B]
    // Get the object of DataInputStream
   [B] DataInputStream in = new DataInputStream(fstream);[/B]
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

I know we need an input stream of data, to transfer data from textfile.txt to program. these datas will transfer to buffer space.

Will buffer space allocated for a JAVA program after compile?

What is difference between FileInputStream and DataInputStream in this code?

You can read the docs.

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Class FileInputStream