BufferedWriter class methods in Java

java.io.BufferedWriter

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.


Some methods of BufferedWriter class.


close()This method closes the stream, flushing it first.


flush()This method flushes the stream.


newLine()This method writes a line separator.


write(int)This method writes a single character.


write(char[], int, int)This method writes a portion of an array of characters.


write(String, int, int)This method writes a portion of a String.


BufferedWriter write(String, int, int) in Java

write(String, int, int): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.write(String s, int off, int len) throws IOException

This method takes three arguments. This method writes a portion of a String.

Parameters: Three parameters are required for this method.

s: String to be written.

off: Offset from which to start reading characters.

len: Number of characters to be written.

Throws:

1. IndexOutOfBoundsException - If off is negative, or off + len is greater than the length of the given string.

2. IOException - If an I/O error occurs.

Approach 1: When no exception 

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite3 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        String s = "hello java program";
        int off = 0, len = 10;
        bufferedWriter.write(s, off, len);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Successfully writes

hello.txt = > hello java

Approach 2: IndexOutOfBoundsException 

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite3 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        String s = "hello java program";
        int off = -1, len = 10;
        bufferedWriter.write(s, off, len);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -1, end 9, length 18 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3734) at java.base/java.lang.String.getChars(String.java:873) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:229)



Approach 3: IOException

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite3 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        String s = "hello java program";
        int off = 0, len = 10;
        bufferedWriter.close();
        bufferedWriter.write(s, off, len);

        System.out.println("Successfully writes");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224)


BufferedWriter write(char[], int, int) in Java

write(char[], int, int): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.write(char[] cbuf, int off, int len) throws IOException

This method takes three arguments. This method writes a portion of an array of characters.

Ordinarily, this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed.

Parameters: Three parameters are required for this method.

cbuf: A character array.

off: Offset from which to start reading characters.

len: Number of characters to write.

Returns: NA

Throws:

1. IndexOutOfBoundsException - If off is negative, or len is negative, or off + len is negative or greater than the length of the given array.

2. IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite2 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };
        int off = 0, len = 3;
        bufferedWriter.write(cbuf, off, len);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Successfully writes

hello.txt => abc

Approach 2: IndexOutOfBoundsException 

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite2 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };
        int off = 0, len = 10;
        bufferedWriter.write(cbuf, off, len);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.io.BufferedWriter.write(BufferedWriter.java:174)



Approach 3: IOException

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite2 {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };
        int off = 0, len = 3;
        bufferedWriter.close();
        bufferedWriter.write(cbuf, off, len);

        System.out.println("Successfully writes");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:171)


BufferedWriter write(int) in Java

write(int): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.write(int c) throws IOException

This method takes one argument. This method writes a single character.

Parameters: One parameter is required for this method.

c: int specifying a character to be written.

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        int c = 'a';
        bufferedWriter.write(c);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Successfully writes

hello.txt => a

Approach 2: IOException 

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterwrite {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        int c = 'a';
        bufferedWriter.close();
        bufferedWriter.write(c);

        System.out.println("Successfully writes");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:132)


BufferedWriter newLine() in Java

newLine(): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.newLine() throws IOException

This method writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

Parameters: NA

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriternewLine {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.newLine();
        System.out.println("Successfully writes a line separator");
        bufferedWriter.close();
    }
}

Output:

Successfully writes a line separator


Approach 2: IOException 

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriternewLine {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.close();
        bufferedWriter.newLine();
        System.out.println("Successfully writes a line separator");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224) at java.base/java.io.Writer.write(Writer.java:249) at java.base/java.io.BufferedWriter.newLine(BufferedWriter.java:246)


BufferedWriter flush() in Java

flush(): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.flush() throws IOException

This method flushes the stream.

Parameters: NA

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterflush {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.flush();

        System.out.println("Successfully flushes buffer stream");
        bufferedWriter.close();
    }
}

Output:

Successfully flushes buffer stream


Approach 2: IOException

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterflush {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.close();
        bufferedWriter.flush();

        System.out.println("Successfully flushes buffer stream");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:117) at java.base/java.io.BufferedWriter.flush(BufferedWriter.java:256)


BufferedWriter close() in Java

close(): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.close() throws IOException

This method closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.

Note:

Closing a previously closed stream has no effect.

Parameters: NA

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach

Java

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterclose {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter =
new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.close();
        System.out.println("Successfully closed the write buffer");
    }
}

Output:

Successfully closed the write buffer


db.grantPrivilegesToRole() in mongoDB

grantPrivilegesToRole(rolename, privileges, writeConcern?)

This method grants additional privileges to a user-defined role.


Syntax:

db.grantPrivilegesToRole(rolename, privileges, writeConcern?) 


Example 1: When the role is user-defined and present.

MongoDB

db.grantPrivilegesToRole(

  "myAdmin",

  [

    {

      resource: { db: "admin", collection: "" },

      actions: [ "insert" ]

    },

    {

      resource: { db: "admin", collection: "system.js" },

      actions: [ "find" ]

    }

  ]

)



Example 2: When the role is user build-in.

MongoDB

db.grantPrivilegesToRole(

    "dbAdmin",
 
    [
 
      {
 
        resource: { db: "admin", collection: "" },
 
        actions: [ "insert" ]
 
      },
 
      {
 
        resource: { db: "admin", collection: "system.js" },
 
        actions: [ "find" ]
 
      }
 
    ]
 
  )


Output:

uncaught exception: Error: dbAdmin@admin is a built-in role and cannot be modified :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.grantPrivilegesToRole@src/mongo/shell/db.js:1731:15
@(shell):1:1


Example 3: When the role is not present.

MongoDB

db.grantPrivilegesToRole(

    "newRole",
 
    [
 
      {
 
        resource: { db: "admin", collection: "" },
 
        actions: [ "insert" ]
 
      },
 
      {
 
        resource: { db: "admin", collection: "system.js" },
 
        actions: [ "find" ]
 
      }
 
    ]
 
  )


Output:

uncaught exception: Error: Role newRole@admin not found :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.grantPrivilegesToRole@src/mongo/shell/db.js:1731:15
@(shell):1:1


db.getUser() in mongoDB

getUser(username, { showPrivileges?, showCredentials? }?)

This method returns user information for a specified user. Run this method on the user’s database.

Note:

The user must exist in the database on which the method runs.

Syntax:

db.getUser(username, { showPrivileges?, showCredentials? }?)


Example 1: When showPreviliges and showCredentials not present.

use admin

db.getUser("dbUser")


MongoDB

db.getUser("dbUser")

Output:

{
    "_id" : "test.dbUser",
    "userId" : UUID("4a722cfc-cd31-40a3-a4dd-410b7bc86d70"),
    "user" : "dbUser",
    "db" : "test",
    "roles" : [
            {
                    "role" : "dbAdmin",
                    "db" : "test"
            },
            {
                    "role" : "readWrite",
                    "db" : "test"
            }
    ],
    "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
    ]
}



Example 2: When showPreviliges and showCredentials are present.


db.getUser("dbUser", { showPrivileges:true, showCredentials:true })



MongoDB

db.getUser("dbUser", { showPrivileges:true, showCredentials:true })

Output:

{
    "_id" : "test.dbUser",
    "userId" : UUID("4a722cfc-cd31-40a3-a4dd-410b7bc86d70"),
    "user" : "dbUser",
    "db" : "test",
    "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
    ],
    "credentials" : {
            "SCRAM-SHA-1" : {
                    "iterationCount" : 10000,
                    "salt" : "kQBGbXMN55QQ5XPJFxKj/g==",
                    "storedKey" : "SfOh4giJr0fZMp6Y7YFuE9pGjQY=",
                    "serverKey" : "86ZjppgA6YBg4KcUFJi3g1CDSfQ="
            },
            "SCRAM-SHA-256" : {
                    "iterationCount" : 15000,
                    "salt" : "hUn8Q1UBzbdbp2HqMI6quMooT0Ba+j2WJqKoFQ==",
                    "storedKey" : "2I+aF/dqiXfShQeetrcqa8L2daRtJt1gRGHi6C+yuEs=",
                    "serverKey" : "hHU86IOBAg9m2mvTB74c6iwJ58dmnD04ozFTEpbKqFg="
            }
    },
    "roles" : [
            {
                    "role" : "dbAdmin",
                    "db" : "test"
            },
            {
                    "role" : "readWrite",
                    "db" : "test"
            }
    ],
    "inheritedRoles" : [
            {
                    "role" : "readWrite",
                    "db" : "test"
            },
            {
                    "role" : "dbAdmin",
                    "db" : "test"
            }
    ],
    "inheritedPrivileges" : [
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : ""
                    },
                    "actions" : [
                            "bypassDocumentValidation",
                            "changeStream",
                            "collMod",
                            "collStats",
                            "compact",
                            "convertToCapped",
                            "createCollection",
                            "createIndex",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "dropDatabase",
                            "dropIndex",
                            "emptycapped",
                            "enableProfiler",
                            "find",
                            "insert",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheIndexFilter",
                            "planCacheRead",
                            "planCacheWrite",
                            "reIndex",
                            "remove",
                            "renameCollectionSameDB",
                            "storageDetails",
                            "update",
                            "validate"
                    ]
            },
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : "system.js"
                    },
                    "actions" : [
                            "changeStream",
                            "collStats",
                            "convertToCapped",
                            "createCollection",
                            "createIndex",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "dropIndex",
                            "emptycapped",
                            "find",
                            "insert",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheRead",
                            "remove",
                            "renameCollectionSameDB",
                            "update"
                    ]
            },
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : "system.profile"
                    },
                    "actions" : [
                            "changeStream",
                            "collStats",
                            "convertToCapped",
                            "createCollection",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "find",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheRead"
                    ]
            }
    ],
    "inheritedAuthenticationRestrictions" : [ ]
}



Example 3: When showPreviliges is present.

db.getUser("dbUser", { showPrivileges:true})


MongoDB

db.getUser("dbUser", { showPrivileges:true })

Output:

{
    "_id" : "test.dbUser",
    "userId" : UUID("4a722cfc-cd31-40a3-a4dd-410b7bc86d70"),
    "user" : "dbUser",
    "db" : "test",
    "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
    ],
    "roles" : [
            {
                    "role" : "dbAdmin",
                    "db" : "test"
            },
            {
                    "role" : "readWrite",
                    "db" : "test"
            }
    ],
    "inheritedRoles" : [
            {
                    "role" : "readWrite",
                    "db" : "test"
            },
            {
                    "role" : "dbAdmin",
                    "db" : "test"
            }
    ],
    "inheritedPrivileges" : [
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : ""
                    },
                    "actions" : [
                            "bypassDocumentValidation",
                            "changeStream",
                            "collMod",
                            "collStats",
                            "compact",
                            "convertToCapped",
                            "createCollection",
                            "createIndex",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "dropDatabase",
                            "dropIndex",
                            "emptycapped",
                            "enableProfiler",
                            "find",
                            "insert",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheIndexFilter",
                            "planCacheRead",
                            "planCacheWrite",
                            "reIndex",
                            "remove",
                            "renameCollectionSameDB",
                            "storageDetails",
                            "update",
                            "validate"
                    ]
            },
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : "system.profile"
                    },
                    "actions" : [
                            "changeStream",
                            "collStats",
                            "convertToCapped",
                            "createCollection",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "find",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheRead"
                    ]
            },
            {
                    "resource" : {
                            "db" : "test",
                            "collection" : "system.js"
                    },
                    "actions" : [
                            "changeStream",
                            "collStats",
                            "convertToCapped",
                            "createCollection",
                            "createIndex",
                            "dbHash",
                            "dbStats",
                            "dropCollection",
                            "dropIndex",
                            "emptycapped",
                            "find",
                            "insert",
                            "killCursors",
                            "listCollections",
                            "listIndexes",
                            "planCacheRead",
                            "remove",
                            "renameCollectionSameDB",
                            "update"
                    ]
            }
    ],
    "inheritedAuthenticationRestrictions" : [ ]
}