scanner class in java - java

Hey I'm trying to compile the following piece of code to basically read stuff from a file but it refuses to work. it gives me an java.io.FILENOTFOUNDEXCEPTION error at line4. help would be appreciated.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}

Try putting the absolute path to the file, like
c:\\java\\matrix1.txt or /home/user/java/matrix1.txt
=== OOPS
You need to catch the Exception that's being thrown. Here's a couple options:
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
OR
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner sc = null;
try {
scanner = new Scanner(fin);
}
catch(FileNotFoundException e) {
System.out.println("File does not exist...");
return;
}
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}

Make sure matrix1.txt is in your src folder if you're using Eclipse.

If you're using an IDE such as Netbeans/Eclipse, you need to put the file to be read in the project folder. This is usually 1 level above the src folder.
A good alternative in case you can't find the folder is to try and create a file. That way, you know where the file was created and you can place the file you want to read in that same folder.

Related

reading text from a relative file path

I have an absolute file path in my java program that contains some text. This is the code:
import java.io.*;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
File rules=new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
Scanner scan=new Scanner(rules);// scans the file 'rules'
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());// outputs 'rules' to console
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
Here, the code works just fine. The output I get is whatever is stored in the file, which is:
The rules of the game are:
You must answer 15 multiple-choice questions correctly in a row to win the jackpot.
You may quit at any time and keep the earnings.
However, what I need is a relative file path so that it runs on any laptop.
In an attempt to do that, I did:
import java.io.*;
import java.net.URI;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
// Two absolute paths
File absolutePath1 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
File absolutePath2 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1");
// convert the absolute path to URI
URI path1 = absolutePath1.toURI();
URI path2 = absolutePath2.toURI();
// create a relative path from the two paths
URI relativePath = path2.relativize(path1);
// convert the URI to string
String path = relativePath.getPath();
Scanner scan=new Scanner(path);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
This does not display the text I need. it just displays "GameshowRules.txt".
How do I get it to output the text stored in the file?
Thanks
Try to use BufferedReader and FileReader. My "data.txt" file is in the same folder as the java program, and works just fine.
I guess you know where will be file of your own program, so you can paste relative path to it.
It looks like this
public class Project {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String data;
while ((data = reader.readLine()) != null) {
System.out.println(data);
}
}
}

Getting unhandled exception error when trying to read a file while using try/catch block

I am trying to create a program which reads a .java file then places each line into an ArrayList:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class H01_43 {
public static void main(String[] args) {
Scanner userInput = new Scanner( System.in );
System.out.println("Please enter the file name.");
String fileName = userInput.nextLine();
TextFile file1 = new TextFile();
file1.createArray(fileName);
userInput.close();
}
}
class TextFile{
public TextFile(){
}
public void createArray(String pFileName){
String currentLine = "";
ArrayList<String> mList = new ArrayList<>();
try{
Scanner userFile = new Scanner(newFile(pFileName));
while(userFile.hasNextLine()){
currentLine = userFile.nextLine();
mList.add(currentLine);
}
}catch(FileNotFoundException exception){
e.printStackTrace();
}finally{
userFile.close();
}
}
}
I keep getting the following error message:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
Unhandled exception type FileNotFoundException
at TextFile.createArray(H01_43 make a java file into txt file.java:47)
at H01_43.main(H01_43 make a java file into txt file.java:27)
I tried working with a tutor who said my code looks fine, but somehow I continue generating this error and therefore can not compile or test my code.
I have actually been struggling with this problem since last semester and just figured it out. Here is my method with the changes:
public void createArray(String pFileName){
String currentLine = "";
ArrayList<String> mList = new ArrayList<>();
try{
Scanner userFile = new Scanner(new File(pFileName));
while(userFile.hasNextLine()){
currentLine = userFile.nextLine();
mList.add(currentLine);
}
}catch(FileNotFoundException exception){
}
}
First problem was that newFile was supposed to be new File but my main issue was that I needed to remove finally and userFile.close(). Am unsure why this is the case and would appreciate it if anyone has some insight for me.

How to make a new directory in some other directory, other than the directory in which i ran my program?

I am new to file handling. I am using arch Linux and in the following code I am compiling and running my code from the java directory but i want to create the new directory in the miniproject directory i tried changing the current working directory but the new directory is still made in the java directory. What is wrong with this and how do i go about doing what i want. Thanks in Advance.
package miniproject;
import java.io.*;
import java.util.*;
public class manager{
public int password;
public static Scanner sc = new Scanner (System.in);
public static void main(String args[]){
addgenre();
}
public static void addgenre (){
System.out.println("Enter the name of the new genre to be added to
the inventory.\nenter -1 to abort.");
String str = sc.nextLine();
if(!(str.equals("-1"))){
genre g = new genre(str);
System.setProperty("/home/qwerty/Documents/codes/java/", "/home/qwerty/Documents/codes/java/miniproject/");
File file = new File(str);
if (!file.exists()) {
if (file.mkdirs()) {
System.out.println("Directory is created!");
}
else
{
System.out.println("Failed to create directory!");
}
}
}
}
}

Reset the file pointer back to starting position

Is there any way I can reuse the Scanner object to read the same file again.
There is RandomAccessFile class that provides random access (seek) but I am looking for some code that uses Scanner. I know how to go to the stating position of the file by creating a new Scanner object, but the code looks messy.
Is there a neat and short method to do the same.
Thanks in advance:-)
Also could you suggest good source/tutorial for learning file handling :p
Here is what I am trying to do:
Container.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
public class Container {
private Scanner sc;
private Formatter f;
void openFile() throws FileNotFoundException{
sc=new Scanner(new File("source"));
}
void readData(){
while(sc.hasNext()){
System.out.println(sc.next());
}
}
void readlineData(){
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
void closeFile(){
sc.close();
}
void addData() throws FileNotFoundException{
f=new Formatter("source");
f.format("%s%s", "hi "," hello");
}
}
Client.java
import java.io.FileNotFoundException;
public class Client {
public static void main(String[] args) throws FileNotFoundException {
Container c=new Container();
try {
c.openFile();
} catch (FileNotFoundException e) {
System.out.println("No file with this name");
}
//reading word by word
c.readData();//there is content already in the file
//reading line by line
c.readlineData();
//changing the content of the file
c.addData();
//reading the file again
c.readData();
//closing the file
c.closeFile();
}
}
Here i have made a client and a container class.
In the container class i have methods to create a file,read file word by word ,read line by liine and close file.
In the client class i have called these methods .

FileNotFoundException on .dat file

Propably it's simple error but I'm stuck. I keep a .dat file with a text I want to read in the program in the same package as main and base class, and I've got a FileNotFoundException. I tried to change the file on .txt, getting the URI syntax, but that didn't help. Where's the point?
The main class:
package syseks;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
public class main {
public static syseks.base ba;
public main(syseks.base ba){
ba = this.ba;
}
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
ba = new base();
String[] py = ba.loadData('p');
System.out.print(py);
}
}
And the loadData method from base class:
public String[] loadData(char param) throws FileNotFoundException{
List<String> strlist = new ArrayList<String>();
if(param == 'p'){
Scanner sc = new Scanner(new File("py.dat")); //HERE'S THE CRASH
while(sc.hasNextLine()){
strlist.add(sc.nextLine());
}
}
else{
Scanner sc = new Scanner(new File("wy.dat"));
while(sc.hasNextLine()){
strlist.add(sc.nextLine());
}
}
String[] da = strlist.toArray(new String[0]);
return da;
}
Supply an absolute path to the File constructor argument. Something like:
Scanner sc = new Scanner(new File("/home/foo/proj/myapp/src/syseks/py.dat"));
Display the current directory using System.getProperty("user.dir"). Make sure it's the directory in which you've saved the .dat file.

Categories

Resources