Tuesday, October 4, 2011

SCJP 6 Part IV - File IO

// create new file if one doesn't exist
File file = new File("myTextFile.txt");
boolean isSuccessfullyCreated = file.createNewFile();
if (isSuccessfullyCreated) {
System.out.println("File has been created successfully!");
} else {
System.out.println("Failed creating file!");
}

// create an object to write to the file, remove the old content
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("New Content");
fileWriter.write("\n");
fileWriter.write("Added String");
fileWriter.flush();
fileWriter.close();

// another way to write to the file, remove the old content
PrintWriter printWriter = new PrintWriter(file);
printWriter.println("Another content");
printWriter.println("Another added content");
printWriter.flush();
printWriter.close();

// advanced way to write to the file, remove the old content
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("The new content");
bufferedWriter.newLine();
bufferedWriter.write("The added content");
bufferedWriter.flush();
bufferedWriter.close();

// create an object to read from the file
FileReader fileReader = new FileReader(file);
StringBuilder sb = new StringBuilder();
while (true) {
int content = fileReader.read();

if (content == -1) {
System.out.println("The content is : " + sb);
break;
} else {
sb.append((char) content);
}
}
fileReader.close();

// advanced way to read from the file
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder sb1 = new StringBuilder();
while (true) {
String content = bufferedReader.readLine();

if (content == null) {
System.out.println("The content is : " + sb1);
break;
} else {
sb1.append(content);
sb1.append("\n");
}
}
bufferedReader.close();

// console
Console console = System.console();

System.out.print("Type something : ");
String typed = console.readLine();
System.out.println("You typed : " + typed);

System.out.print("Type your secret : ");
String secret = String.valueOf(console.readPassword());
System.out.println("Your secret was : " + secret);

0 comments:

 

©2009 Stay the Same | by TNB