File, Stream, Reader and Writer

 

Stream hierarchy

IO_InputOutputStreams

IO_InputOutputReadersWriters

 

Programs:

File Creation

// 1 way of creating a file
		File simpleFile = new File(
				"C:\\Users\\cccc\\workspace\\ccccc-B3\\cccc.txt");
                simpleFile ..createNewFile();
// 2nd way of creating a file
			String fileName = "cap.txt";
			String path = System.getProperty("user.dir");
			String absolutePath = path + File.separator + fileName;

			File capitalFile = new File(absolutePath);
			capitalFile.createNewFile();

Read from a file

//One way 
try (FileInputStream fis = new FileInputStream(simpleFile);
				BufferedInputStream bis = new BufferedInputStream(fis);
				DataInputStream dis = new DataInputStream(bis);) {

while (dis.available() != 0) {
				System.out.println(dis.readLine());
			}
} catch (IOException oie) {

		}

//Alternative way
FileReader fr = new FileReader(capitalFile);
			BufferedReader br = new BufferedReader(fr);
			String line;

			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

Wirting on to a file

try {
			String additionalText = "This information goes to cap file";
			String fileName = "cap.txt";
			String path = System.getProperty("user.dir");
			String absolutePath = path + File.separator + fileName;

			File capFile = new File(absolutePath);

			if (!capFile.exists()) {
				capFile.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(capFile,true);
		    //TODO Appending data in to existing file
			fos.write(additionalText.getBytes());
			fos.flush();
			fos.close();
			
			//Another way
			FileWriter fw = new FileWriter(capFile, true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write("\nthrough Buffered writer. second time");
			bw.flush();
			bw.close();
		} catch (IOException e) {
		}