Scanner- trouble finding file - java

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"));

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();
}
}
}

Reading a file in Java with Scanner

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();

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.

Change a program to accept command line arguments

I have the following code and would like to modify it to accept command line arguments instead of reading a file using scanner. Can you point me to some change I need to make in the code in order to do so ? Any help is appreciated. I will have a file called prgm.cmd and will execute it on UNIX as follows. prgm.cmd is the actual argument !
java Commander prgm.cmd
right now I am only able to have the program work by using
java Commander < prgm.cmd
CODE
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Commander
{
public static void main(String[] args)
{
Map<String,Integer> expression = new HashMap<String,Integer>();
ArrayList<String> list = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
list.add(sc.nextLine());
if(!sc.hasNextLine()) break;
}
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<String> PRINT = new ArrayList<String>();
for(String element : list) {
StringTokenizer st = new StringTokenizer(element);
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
} else {
while(st.hasMoreTokens())
PRINT.add(st.nextToken());
System.out.println(expression.get(PRINT.get(1)));
PRINT.clear();
}
}
}
}
SAMPLE COMMAND FILE: PRGM.CMD
A = 6
C = 14
PRINT C
B = 12
C = 8
PRINT A
OUTPUT
14
6
public static void main(String[] args)
// ^^^^^^^^^^^^^
When you run your program with something like:
java progname arg1 arg2
the arguments appear in the string array handed to main(). You just extract them from there and do what you need.
The following small (but complete) program shows this in action. It will echo back your arguments, one per line:
public class Test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println (args[i]);
}
}
That's to get the commands as arguments to the program.
If, instead, you want to still have the commands in a file and just supply the file name to the program, you simply need to change your scanner to use a file based reader rather than System.in. The following program accepts a file name argument then echos it to the screen:
import java.io.FileInputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try {
Scanner sc = new Scanner (new FileInputStream(args[0]));
while (sc.hasNextLine())
System.out.println (sc.nextLine());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
You can even make it selectable, like UNIX filter programs using - to indicate standard input.
If you want to use a file if provided but revert to standard input if not, you can do something like:
Scanner sc;
if (args.length > 0)
sc = new Scanner (new FileInputStream(args[0]));
else
sc = new Scanner (System.in);
// Now just use scanner as before

Modify or Delete Data in a File

Today I was trying the algorithm for modifying and deleting data inside a file using Java in Windows platform.
1st : create a temporaryFile
2nd : write the data you wanted inside the originalFile into a String and to the temporaryFile
3rd : rename temporaryFile to originalFile.
The Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class testing{
private static String temp;
public static void main(String [] args)
{
try{
File tempFile = File.createTempFile("haha\\temporary", ".txt"); //create a temporary file in haha folder
FileWriter writer = new FileWriter(tempFile);
Scanner input = new Scanner(new File("haha\\testing.txt")); //get input from testing.txt
temp = input.next();
writer.write(temp);
writer.close();
File origFile = new File("haha\\testing.txt");
tempFile.renameTo(origFile);
}
catch ( FileNotFoundException fileNotFoundException ){}
catch(IOException ioException){}
}
}
In the above code , the textFile to be edited is located inside a folder name haha which is located inside another folder together with the testing.class.I've tried this code to no avail , the originalTextFile has no changes .
If you have your file in the same directory, you don't need to pass the path to the File constructor.
Scanner input = new Scanner(new File("testing.txt"));
This should do it.
You need to close the Scanner object to make the changes, the underlying operating system has a file lock that must be released.
input.close();
File origFile = new File("haha\\testing.txt");

Categories

Resources