24
loading...
This website collects cookies to deliver better user experience
//Opening an inputStream and convert the file name to FileInputStream object
Scanner inputStream = new Scanner(new FileInputStream("marks.txt"));
int counter = 0;
while (inputStream.hasNextInt()) { //Returns true if there is next int in the file
int number = inputStream.nextInt(); //Scans the next token of the input as an int.
System.out.println(number);
}
inputStream.close();
1
2
3
//The program opens the text file
BufferedReader inputStream = new BufferedReader(new FileReader("quots.txt")); //FileReader to convert the file name to object
String i= inputStream.readLine();
while (i!=null){
System.out.println(i);
i= inputStream.readLine();
}
123 hello
1 23d I am on console!
BufferedReader
class has no constructor takes a file name as it's argument (We need to convert the file name to object).readLine
and read
.read
method reads a single character, and returns an int
that corresponds to the character you read.(You need to cast that int to get the character), ex:
char next = (char)inputStram.read();
readLine
method returns null
and read
method returns -1.Unlike class Scanner
, the class BufferedReader
has no
constructor to deal with numbers. You have to read the numbers as a string then convert the string to a numeric type, ex:
Integer.parseInt();
Double.pareDouble();
If there are multiple numbers in a single line:
readLine()
StringTokenizer
to decompose the string into tokens.PrintWriter
is the preferred class to write to a text file.//Opening the file
PrintWriter outputStream = new PrintWriter(new FileOutputStream("shahed.txt")); //use FileOutputStream to convert the file name to object
//writing to the file
outputStream.print("this line written from a java program");
//close the connection
outputStream.close();
this line written from a java program
File
class.
PrintWriter
class has no constructor takes a file name as it's argument (We need to convert the file name to object).flush()
close()
include an invocation of flush()
.PrintWriter outputStreamToAppend = new PrintWriter(new FileOutputStream("shahed.txt", true));
PrintWriter
class throw FileNotFoundException
and it indicates that file can't be created.File
classFile
class constructor takes a string name (Abstract name) and checks the properties if that name, ex exists
methods checks if name is exists, and isDirectory()
tests if the name the name of a directory.
ex:
File file = new File ("Fruits.txt");
if (!file.canRead()){
System.out.println("The file can not be read!")
}
setReadOnly()
canWrite()
delete()
getName()
getPath()
length()