8000 file handling · harshspandey1/DSA-Bootcamp-Java@237f573 · GitHub
[go: up one dir, main page]

Skip to content

Commit 237f573

Browse files
file handling
1 parent f29e89c commit 237f573

File tree

10 files changed

+324
-4
lines changed

10 files changed

+324
-4
lines changed

lectures/06-conditions-loops/code/.idea/misc.xml

Lines changed: 1 addition & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.io.*;
2+
3+
class Input {
4+
static void input() {
5+
try (InputStreamReader isr = new InputStreamReader(System.in)) {
6+
System.out.print("Enter some letters:");
7+
int letters = isr.read();
8+
while(isr.ready()) {
9+
System.out.println((char) letters);
10+
letters = isr.read();
11+
}
12+
// isr.close();
13+
System.out.println();
14+
} catch (IOException e) {
15+
System.out.println(e.getMessage());
16+
}
17+
18+
try (FileReader fr = new FileReader("note.txt")) {
19+
int letters = fr.read();
20+
while(fr.ready()) {
21+
System.out.println((char)letters);
22+
letters = fr.read();
23+
}
24+
// fr.close();
25+
System.out.println();
26+
} catch (IOException e) {
27+
System.out.println(e.getMessage());
28+
}
29+
30+
// byte to char stream and then reading char stream
31+
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
32+
System.out.println("You typed: " + br.readLine());
33+
} catch (IOException e) {
34+
System.out.println(e.getMessage());
35+
}
36+
37+
try (BufferedReader br = new BufferedReader(new FileReader("note.txt"))) {
38+
while (br.ready()) {
39+
System.out.println(br.readLine());
40+
}
41+
} catch (IOException e) {
42+
System.out.println(e.getMessage());
43+
}
44+
}
45+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.io.*;
2+
import java.io.IOException;
3+
import java.util.Scanner;
4+
5+
class Main {
6+
public static void main(String[] args) {
7+
8+
// create
9+
try {
10+
File fo = new File("new-file.txt");
11+
fo.createNewFile();
12+
} catch (IOException e) {
13+
System.out.println(e.getMessage());
14+
}
15+
16+
// write in the file
17+
try {
18+
FileWriter fw = new FileWriter("new-file.txt");
19+
fw.write("सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच:");
20+
fw.close();
21+
} catch (IOException e) {
22+
System.out.println(e.getMessage());
23+
}
24+
25+
// reading from a file
26+
try (BufferedReader br = new BufferedReader(new FileReader("new-file.txt"))) {
27+
while (br.ready()) {
28+
System.out.println(br.readLine());
29+
}
30+
} catch (IOException e) {
31+
System.out.println(e.getMessage());
32+
}
33+
34+
// create
35+
try {
36+
File fo = new File("random.txt");
37+
fo.createNewFile();
38+
if(fo.delete()) {
39+
System.out.println(fo.getName());
40+
}
41+
} catch (IOException e) {
42+
System.out.println(e.getMessage());
43+
}
44+
45+
46+
47+
}
48+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.io.*;
2+
3+
class Output {
4+
static void output() {
5+
// output
6+
OutputStream os = System.out;
7+
// os.write(😍); // range is exceeded
8+
9+
try (OutputStreamWriter osw = new OutputStreamWriter(System.out)) {
10+
osw.write("Hello World");
11+
osw.write(97);
12+
osw.write(10);
13+
osw.write('A');
14+
osw.write('\n');
15+
char[] arr = "hello world".toCharArray();
16+
osw.write(arr);
17+
// osw.write(😍);
18+
} catch (IOException e) {
19+
System.out.println(e.getMessage());
20+
}
21+
22+
try (FileWriter fw = new FileWriter("note.txt", true)) {
23+
fw.write("this should be appended");
24+
} catch (IOException e) {
25+
System.out.println(e.getMessage());
26+
}
27+
28+
try (BufferedWriter bw = new BufferedWriter(new FileWriter("note.txt"))) {
29+
bw.write("Hare Krishna");
30+
} catch (IOException e) {
31+
System.out.println(e.getMessage());
32+
}
33+
}
34+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hare Krishna
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<project>
2+
<modelVersion>4.0.0</modelVersion>
3+
<groupId>mygroupid</groupId>
4+
<artifactId>myartifactid</artifactId>
5+
<version>0.0-SNAPSHOT</version>
6+
<dependencies>
7+
<dependency>
8+
<groupId>junit</groupId>
9+
<artifactId>junit</artifactId>
10+
<version>4.12</version>
11+
<type>jar</type>
12+
</dependency>
13+
<dependency>
14+
<groupId>com.googlecode.json-simple</groupId>
15+
<artifactId>json-simple</artifactId>
16+
<version>1.1.1</version>
17+
<type>jar</type>
18+
</dependency>
19+
<dependency>
20+
<groupId>org.hamcrest</groupId>
21+
<artifactId>hamcrest-core</artifactId>
22+
<version>1.3</version>
23+
<type>jar</type>
24+
</dependency>
25+
</dependencies>
26+
<build>
27+
<plugins>
28+
<plugin>
29+
<groupId>de.qaware.maven</groupId>
30+
<artifactId>go-offline-maven-plugin</artifactId>
31+
<version>1.2.5</version>
32+
<configuration>
33+
<dynamicDependencies>
34+
<DynamicDependency>
35+
<groupId>org.apache.maven.surefire</groupId>
36+
<artifactId>surefire-junit4</artifactId>
37+
<version>2.20.1</version>
38+
<classifier></classifier>
39+
<repositoryType>PLUGIN</repositoryType>
40+
</DynamicDependency>
41+
<DynamicDependency>
42+
<groupId>com.querydsl</groupId>
43+
<artifactId>querydsl-apt</artifactId>
44+
<version>4.2.1</version>
45+
<classifier>jpa</classifier>
46+
<repositoryType>MAIN</repositoryType>
47+
</DynamicDependency>
48+
</dynamicDependencies>
49+
</configuration>
50+
</plugin>
51+
</plugins>
52+
</build>
53+
</project>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{ pkgs }: {
2+
deps = [
3+
pkgs.graalvm17-ce
4+
pkgs.maven
5+
pkgs.replitPackages.jdt-language-server
6+
pkgs.replitPackages.java-debug
7+
];
8+
}
Binary file not shown.
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
IOException :
2+
An IOException is any unexpected problem the JVM encounters while attempting to run a program.
3+
When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads
4+
data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is
5+
otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions.
6+
7+
Streams :
8+
In its most basic form a stream simply represents a sequence of data (bytes or unicode characters) in some sort of a sequential queue.
9+
Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information.
10+
A stream is linked to a physical device by the Java I/O system.
11+
Java implements streams within class hierarchies defined in the java.io package.
12+
The same I/O classes and methods can be applied to different types of devices.
13+
14+
Java defines two types of streams:
15+
-Byte streams provide a convenient means for handling input and output of bytes.
16+
Byte streams contain binary data this useful for things such as reading and writing to files - just imagine opening up an image file in a text editor, that is a good representation of byte data.
17+
EXAMPLE : Use a byte stream ex : InputStream etc and type 'ᛞ'. This exceeds the 256 limit of 8-bit characters hence it will show some other
18+
value. If we type 'ᛞ' in char-stream such as InputStreamReader it will show 'ᛞ' only.
19+
20+
OutputStream os = System.out;
21+
os.write('ᛞ'); // will not show anything (or garbage) cuz range exceeded. ᛞ is Unicode.
22+
23+
24+
-Character streams provide a convenient means for handling input and output of characters. They use Unicode and,
25+
therefore, can be internationalized, good candidate for things like keyboard input and console output.
26+
Also, in some cases, character streams are more efficient than byte streams.
27+
28+
Byte streams are defined by using two class hierarchies.
29+
At the top are two abstract classes: InputStream and OutputStream.
30+
Each of these abstract classes has several concrete subclasses that handle the differences among various devices,
31+
such as disk files, network connections, and even memory buffers.
32+
The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement.
33+
Two of the most important methods are read( ) and write( )
34+
35+
Character streams are defined by using two class hierarchies.
36+
At the top are two abstract classes: Reader and Writer.
37+
Two of the most important methods are read( ) and write( ).
38+
39+
The Predefined Streams :
40+
System.out refers to the standard output stream. By default, this is the console.
41+
System.in refers to standard input, which is the keyboard by default.
42+
System.err refers to the standard error stream, which also is the console by default.
43+
System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
44+
These are byte streams.
45+
46+
NOTE : Names of character streams typically end with Reader/Writer & names of byte streams end with InputStream/OutputStream.
47+
48+
InputStreamReader Class :
49+
EXTENDS READER : Abstract class for reading character streams.
50+
int read() : The character read, as an integer in the range 0 to 65535 (0x00-0xffff),
51+
or -1 if the end of the stream has been reached
52+
Primarily it is used to convert byte streams to character streams.
53+
java.io.InputStreamReader has several overloaded constructors with each taking an InputStream (like System.in, or FileInputStream) as the first parameter.
54+
The InputStreamReader class has a method called close() that will close the stream and releases any system resources associated with it.
55+
The close() method should always be called once you are done with the input stream.
56+
In Java 7 a new feature called try-with-resources was introduced.
57+
Specifically a resource is an object that must be closed after the program is finished with it.
58+
The try-with-resources statement ensures that each resource is closed at the end of the statement.
59+
How do we know if a class is a resource? Simple, if it implements java.lang.AutoCloseable,
60+
the class can be considered a resource.
61+
62+
try-with-resources :
63+
The try-with-resources statement is a try statement that declares one or more resources.
64+
A resource is an object that must be closed after the program is finished with it.
65+
The try-with-resources statement ensures that each resource is closed at the end of the statement.
66+
Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable,
67+
can be used as a resource.
68+
69+
FileReader Class :
70+
The purpose of the FileReader class is to simply read character based files.
71+
The FileReader class implements AutoClosable so we can use the try-with-resources type exception handling.
72+
It also interesting to note that the FileReader class does not define or override any public methods,
73+
so it inherits all of its methods from its superclass InputStreamReader; InputStreamReader is a subclass of Reader
74+
which is a subclass of Object and that describes the class hierarchy.
75+
76+
Object -> Reader -> InputStreamReader -> FileReader
77+
78+
BufferedReader Class : BufferedReader(Reader inputReader)
79+
IT EXTENDS READER. HENCE HAS IT'S OWN read() which is same as InputStreamReader.
80+
The BufferedReader class is used to read text from a character stream.
81+
The BufferedReader class has the same read() method that both InputStreamReader and FileReader use to read a single byte at a time.
82+
The BufferedReader class introduces a method named readLine() which will read an entire line of text which is a huge improvement.
83+
The BufferedReader class implements AutoClosable so we can use the try-with-resources type exception handling.
84+
85+
To obtain a character-based stream that is attached to the console, wrap System.in in a BufferedReader object.
86+
InputStreamReader(InputStream inputStream)
87+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
88+
NOTE : new InputStreamReader(System.in) converts byte stream into char stream.
89+
AND then br is reading that char stream. Which is what we want!
90+
After this statement executes, br is a character-based stream that is linked to the console through System.in.
91+
92+
Writer Classes :
93+
94+
OutputStreamWriter Class :
95+
EXTENDS WRITER
96+
Used to write to character streams.
97+
The OutputStreamWriter class implements AutoClosable so we can use the try-with-resources type exception handling.
98+
There are only four public methods in the OutputStreamWriter class: close(), flush(), getEncoding(), and write().
99+
The write() method has three overloaded versions :
100+
-write(int a) : writes a single character to character stream.
101+
Characters being written is contained in 16 lower bits of the ‘char’ integer value,
102+
rest of the 16 higher bits are ignored by the method.
103+
-write(String str)
104+
-write(char cbuf[])
105+
106+
FileWriter Class :
107+
EXTENDS OutputStreamWriter
108+
The purpose of the FileWriter class is to simply write character based files.
109+
The FileWriter class implements AutoClosable so we can use the try-with-resources type exception handling.
110+
FileWriter class does not define or override any public methods, so it inherits all of its methods from its superclass OutputStreamWriter.
111+
112+
Object -> Writer -> OutputStreamWriter -> FileWriter
113+
114+
BufferedWriter Class :
115+
The BufferedWriter class is used to write text to a character stream.
116+
The BufferedWriter class has three overloaded versions of the write() method.
117+
The BufferedWriter class introduces a method named newLine() which means that you will not have to hardcode in the "\r\n" into your output stream anymore.
118+
The BufferedWriter class implements AutoClosable so we can use the try-with-resources type exception handling.
119+
120+
121+
File Class :
122+
123+
Consider this Windows hard coded path represented as a string: "c:\\Java\\BW\\Sample.txt". If a user attempted to run
124+
your program on a Linux or UNIX OS, your program will fail miserably. That is because the directory separator is '/' in
125+
UNIX as opposed to '\' in Windows. The file class provides us with several tools to dynamically create our directory
126+
and file structure.
127+
128+
Constructors:
129+
File(File parent, String child)
130+
File(String pathname) // not very useful for multi-platform
131+
File(String parent, String child)
132+
File(URI uri)
133+

0 commit comments

Comments
 (0)
0