In: Computer Science
Scanner file = new Scanner ( new File (“test.txt”));
Scanner parse = new Scanner (“A 1 B 2 C 3 D”);
while (parse.hasNext())
System.out.print(parse.next());
try
{
Scanner file = new Scanner(new File(“c:\docs\data.txt”));
int n = 0;
while (file.hasNext())
{
String s = file.nextLine();
if (s.equals(“A”))
n++;
}
System.out.println(“The value of n is “ +n);
file.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
try
{
Scanner file = new Scanner( new File(“test.txt”));
String s = file.nextLine();
}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}
Will this code work correctly? If not how do you fix it.
# PLEASE LEAVE A THUMBS UP.
1.) Scanner file = new Scanner ( new File (“test.txt”));
This code is used to read a text file using java.util.scanner.
It must implement File not found exception or must be catch by the try catch block.
Here in the parameter of the constructor of Scanner the object of the File class is created .
lets have an example-
public class ReadFile
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner file = new Scanner(new File("test.txt"));
int line = 1;
while (file.hasNext())
{
String str = scan.nextLine();
System.out.println((line++) + ": " + str);
}
}
}
2.)
Scanner parse = new Scanner (“A 1 B 2 C 3 D”);
while (parse.hasNext())
System.out.print(parse.next());
OUTPUT : A1B2C3D
// without any spaces, as next does not read spaces , but if you use nextLine() instead then spaces would be printed.
3.)
try
{
Scanner file = new Scanner(new File(“c:\docs\data.txt”));
int n = 0;
while (file.hasNext())
{
String s = file.nextLine();
if (s.equals(“A”))
n++;
}
System.out.println(“The value of n is “ +n);
file.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
Here, the argument inside catch is wrong. Just remember whenever U try to read a a file, File not found expection is a must to be thrown or catch if a try-catch block is used.
For ex,
catch (FileNotFoundException e)
{
e.printStackTrace();
}
4.) No, it will not read whole file for that you need to use a while loop and file.hasnext() function , the hasNext() method returns true if the given file contains another string. Hence why the code will loop if file has another string. Once there are no more Strings in the file, hasNext() returns false.
try
{
Scanner file = new Scanner( new File(“test.txt”));
while(file.hasnext()){
String s = file.nextLine();
System.out.print(s);
}}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}