Reading a file in Java with Scanner - java

I'm trying to get a program to read a text file but it's throwing a FileNotFoundException even though I have the potato.txt file set in the project directory.
import java.io.File;
import java.util.Scanner;
public static void main(String[] args) {
String potato = "potato.txt"; // assume this line can't be changed at all
Scanner scan = new Scanner(new File(potato)); // throws FileNotFoundException
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
}
}
}

Try using the full Path, like this:
File file = new File("C:/temp/potato.txt"); //This is just an example path, look up your files path and put it here.
Scanner scan = new Scanner(file);
Also, don't forget to close your scanner when done (after your while-loop):
scan.close();

Related

Can't read txt file with Scanner in Eclipse (Java)

I'm having difficulty reading a .txt file (words.txt) for a project I'm working on within Eclipse (jre1.8.0_181). I have a copy of words.txt in
String wordsPath = "C:\\Users\\Administrator\\Documents\\words.txt";
as well as in the project directory itself (which I tried to define multiple ways):
String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\\words.txt");
However, when I attempt to establish filein:
Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));
I get a FileNotFoundException on all attempts. Does anybody have any insight into this? I know the files are there; what else am I missing? I have the right imports as well, I believe (import java.io.File; and import java.util.Scanner;). I looked through as many similar questions I could find, no luck. Many thanks!
Both files in below program can be read without any error. Compare and see whether you are doing something wrong.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
try
{
Scanner scanner = new Scanner(new File("words.txt"));
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
Scanner scanner2 = new Scanner(new File("C:\\Users\\prasad.karunagoda\\words2.txt"));
System.out.println(scanner2.nextLine());
System.out.println(scanner2.nextLine());
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
}

How do I make a file's contents scanned and printed?

Using java, I need to make a program that asks the user which file to scan, and to do some work with the data in the file.
My program is supposed to select a file, scan the file for a specific character that the user specifies, and return with how many specific characters there are in that file.
This is my code so far:
import java.io.*;
import java.util.Scanner;
public class CharSearch {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file you want to search.");
String fileInput = scanner.nextLine();
System.out.println("What character would you like to look for in " + fileInput + "?");
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner);
}
}
I imported io and scanner, then set up the scanner to read which file the user inputs. I print back out that file name. The last two lines are where I need help. How can I make the scanner return with the data in the file.
There is a file in my folder called data.txt and all that is written in it is "dataWord." For starters, I want the scanner to read the file and the program to display dataWord, but its not working. I am a rookie, so please work with me. Thanks.
Instead of passing path of file as String pass it as a File
Scanner fileScanner = new Scanner(new File(fileInput));
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
scanner.close();
fileScanner.close();
If the file is an external file or not in your project, you can specify the absolute path of file.
If it is in classpath you can read using ClassLoader
java.io.InputStream inputStream = this.getClassLoader().getResourceAsStream("file_path")
Scanner has a constructor with InputStream

Scanning in file

I'm trying to scan the following sentences into my Java program as strings:
The cat in the hat
The cat sat on the mat
Pigs in a blanket
and then read it into a list using whileloop and hasNextLine()method.
My problem is that I am unsure how to read this in as it is not a designated text file and I must utilizeargs [0]
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) throws FileNotFoundException{
//Opens a scanner into the file
File file = new File( args [0] );
try (Scanner scan = new Scanner(file))
{
ArrayList<String> list = new ArrayList<String>();
while(scan.hasNextLine())
{
list.add(scan.nextLine());
}
}
}
}
If you're just trying to output the list, use a for each style loop is the fastest way to check if you're doing it right.
for (String val : list)
{
System.out.println(val);
}
I think you should replace your existing code with the one below:
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
list.add(scan.nextLine());
}
scan.close();
Use System.in instead of new File(args[0]). System.in reads from the standard input (i.e. whatever is entered in with the keyboard). This should work both on an IDE and with command line input.
I hope this helps.

Reading a file from my desktop and printing each line from it

dear all here i have this code:
File file = new File("flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
String line = in.nextLine();
System.out.println(line);
I want to read from a file and print each line, but this code doesn't work because of some exceptions (throw exception??), how can i put it in a way that it would read from the flowers.txt file, which is on my desktop and will print each line from this file in the console?
Recheck your code
File file = new File("flowers_petal.txt"); // This is not your desktop location.. You are probably getting FileNotFoundException. Put Absolute path of the file here..
while(in.hasNext()){ // checking if a "space" delimited String exists in the file
String line = in.nextLine(); // reading an entire line (of space delimited Strings)
System.out.println(line);
SideNote : use FileReader + BufferedReader for "reading" a file. Use Scanner for parsing a file..
Here you go.. Full code sample. Assuming you put you file in C:\some_folder
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String args[]) {
File file = new File("C:\\some_folder\\flowers_petal.txt");
Scanner in;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are checking for the wrong condition, you need to check for hasNextline() instead of hasNext(). So the loop will be
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
Consider these 2 points :
the current location you are giving in your file is not valid (if
your .java (source) file is not on Desktop), so give the full path
for your file.
the new Scanner(File file) throws FileNotFoundException, so you have to put the code in try-catch block or just use throws.
Your code may look like this :
try {
File file = new File("path_to_Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
try this
public static void main(String[] args) throws FileNotFoundException {
//If your java file is in the same directory as the text file
//then no need to specify the full path ,You can just write
//File file = new File("flowers_petal.txt");
File file = new File("/home/ashok/Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
}
NOTE :I am using linux ,If you are using windows your desktop path would be different
Try this................
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
give your exact path in the FileReader("exact path must be here...")
source: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Scanner- trouble finding file

I'm trying to load a text file into java, but I'm having trouble locating the file within my code.
My file is named 'test.txt' and is saved under src/test.txt , src/fileIOTest/test.txt , and in a resources file, but regardless of how I try to load the file, the program can't seem to locate it. It shows up in the package explorer, but throws a file not found exception.
package fileIOTest;
//This project tests out the scanner system, reading a text file into an array.
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
public class Test {
public void init(){
Scanner sc = null;
try {
sc = new Scanner(new FileReader("/test.txt"));
} catch(IOException e){
e.printStackTrace();// print the error
}
int[] testArray = new int[10];
for(int i = 0; i < 10; i++){
testArray[i] = sc.nextInt();
System.out.println(testArray[i]);
}
}
public static void main(String[] args){
Test fileLoader = new Test();
fileLoader.init();
}
}
Edit: Here's my file system
Ok, try:
File directory = new File("src/test.txt");
Path file = Paths.get(directory.getAbsolutePath());
Scanner sc = new Scanner(file);
Or: Try removing slash might work:
Scanner sc = newScanner(new FileReader("test.txt"));

Categories

Resources