Java Stream Buffer problem

Source: Internet
Author: User

Listen to Zhang Xiaoxiang: teacher about the buffer zone knowledge of the class, found that there are some do not grasp, hands-on tried, and indeed found the problem.

To start with the knowledge of the Java buffer, there is a buffer between the application and IO devices, and there is no buffer for the general stream, but if there is a buffer there is a big problem.

The error code is as follows: to ensure that the problem occurred, I used the bufferedoutputstream to construct a buffer manually.

Import java.io.*;
public class Test {public
	static void Main (string[] args) throws exception{
		DataOutputStream out = new DataOutput Stream (New
							Bufferedoutputstream (
							"1.txt"));
		Out.writechars ("Hello");
		FileInputStream in = new FileInputStream ("1.txt");
		int len = in.available ();
		Byte[] B = new Byte[len];
		int actlen = In.read (b);
		String str = new string (b);
		System.out.println (str);
		
	}	


Have you found anything wrong?

Because if there is no buffer, the application has to communicate with the device every time IO is inefficient, so in order to improve the efficiency of the buffer, write to the device, write the buffer, and wait until there is enough data in the buffer to write the device as a whole. That's the problem, in the last example, when we write Hello, because Hello takes up so little space, it's temporarily stored in a buffer, and then the input stream wants to read it from the file, but it can't read hello because there are no bytes in the file.

Here, the workaround is simple, just call Out.flush () or Out.close (), which is to manually write the data of the buffer to the file.

The correct code is as follows:

Import java.io.*;
public class Test {public
	static void Main (string[] args) throws exception{
		DataOutputStream out = new DataOutput Stream (New
							Bufferedoutputstream (
							"1.txt"));
		Out.writechars ("Hello");
		Out.close ();//inserted
		FileInputStream in = new FileInputStream ("1.txt");
		int len = in.available ();
		Byte[] B = new Byte[len];
		int actlen = In.read (b);
		String str = new string (b);
		System.out.println (str);
		
	}	


The next one is an example of what I've come across, and this example is clearly reacting to the buffer problem.

Import Java.io.BufferedReader;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.GregorianCalendar;
Import Java.util.Scanner;

Import Java.util.StringTokenizer;
        public class Stringtokenizertest {public static void main (string[] args) {employee[] e = new employee[3];
        E[0] = new Employee ("Carl cracker", 75000, 1987, 12, 15);
        E[1] = new Employee ("Harry Hacker", 50000, 1989, 10, 1);
        E[2] = new Employee ("Tony Tester", 40000, 1990, 3, 15);
            try {printwriter out = new PrintWriter (New FileWriter ("1.txt"));
            WriteData (E, out);
            Out.close (); **********************************************************************} catch (Exception E1) {
        E1.printstacktrace (); System.out.println ("******* whether to read the data.")
        ********");
   Scanner in1 = new Scanner (system.in);     String Yes = In1.nextline (); if (Yes.equalsignorecase ("yes")) {try {BufferedReader in = new BufferedReader (New FileReader
                ("1.txt"));
                Employee[] result = ReadData (in);
                for (int i = 0; i < result.length i++) System.out.println (result[i));
            In.close ();
            catch (Exception E2) {e2.printstacktrace (); }} public static employee[] ReadData (BufferedReader in) throws IOException {int length = int
        Eger.parseint (In.readline ());
        Employee[] e = new Employee[length];
            for (int i = 0; i < length; i++) {String line = In.readline ();
            StringTokenizer token = new StringTokenizer (line, "|");
            String name = Token.nexttoken ();
            Double salary = double.parsedouble (Token.nexttoken ());
            int year = Integer.parseint (Token.nexttoken ()); int month = INteger.parseint (Token.nexttoken ());
            int day = Integer.parseint (Token.nexttoken ());
        E[i] = new Employee (name, salary, year, month, day);
    return e;
        public static void WriteData (employee[] e, printwriter out) {out.println (e.length);
            for (int i = 0; i < e.length; i++) {String name = E[i].getname ();
            Double salary = e[i].getsalary ();
            Date date = E[i].gethireday ();
            Calendar C = new GregorianCalendar ();
            C.settime (date);
            int year = C.get (calendar.year);
            int month = C.get (calendar.month) + 1;
            int day = C.get (calendar.day_of_month);
                    OUT.PRINTLN (name + "|" + Salary + "|" + year + "|" + month + "|")

        + day);
    } System.out.println ("******** Write Data Complete ********");
        Class Employee {public employee (String N, double S, int year, int month, int day) {name = N; Salary= S;
        GregorianCalendar calendar = new GregorianCalendar (year, month-1, day);
    Hireday = Calendar.gettime ();
    Public String GetName () {return name;
    Public double getsalary () {return salary;
    Public Date Gethireday () {return hireday;
        The public void Raisesalary (double bypercent) {Double raise = salary * BYPERCENT/100;
    Salary + = raise;
                Public String toString () {return getclass (). GetName () + "[name=" + name + ", salary=" + Salary
    + ", hireday=" + Hireday + "]";

    private String name;

    private double salary;
Private Date Hireday; }

The result is no data being written to the file.

The only error is that Out.close () is not invoked in the main method to flush the data from the buffer to the file. So it's important that you run out of resources and shut down immediately.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.