I'm trying to read a plain text file but somehow FileReader is not finding my text file. I checked the directory using getAbsolutefile() and /Users/djhanz/IdeaProjects/datalab2/pg174.txt is the exact location of the file. I tried datlab2/pg174.txt and everything I possibly could.
Here is my code
public class Program1 {
public static void main(String[] args) {
System.out.println(new File("pg174.txt").getAbsoluteFile());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/Users/djhanz/IdeaProjects/datalab2/pg174.txt")));
while (testScanner.hasNextLine())
{
System.out.println(testScanner.nextLine());
}
}
}
The text file is under the same project directory called datalab.
Can someone please enlighten me?
Use Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
FileReader("/pg174.txt") instead of FileReader("pg174.txt").
package com.example.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(new File("pg174.txt").getPath());
System.out.println(new File("pg174.txt").getAbsoluteFile());
System.out.println(new File("pg174.txt").getAbsolutePath());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
while (testScanner.hasNextLine()) {
System.out.println(testScanner.nextLine());
}
}
}
Output:
Related
On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.
Im trying to use relative path to read a file but the path cant be found.
maxSuccession is the name of my project
This is my workspace path: C:\Programming
This is my project's path C:\Programming\MaxSuccessions\maxSuccessions
This is my filepath C:\Programming\MaxSuccessions\Tests\test1\00.in.txt
package test1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) throws IOException {
String myPath="..\\MaxSuccessions\\Tests\\test1\\";
Scanner sc = new Scanner(new File(myPath+"00.in.txt"));
System.out.println(sc.nextInt());
}
}
If your class file and required file are in the same directory, you can try this code:
public static void main(String[] args) {
String fileName = "00.in.txt"; //relative path from the path of your class.
try {
Scanner sc = new Scanner(Test.class.getResource(fileName).openStream());
System.out.println(sc.nextInt());
} catch (IOException e) {
e.printStackTrace();
}
}
I have a .csv file that I want to load in Java so that afterwards I will be able to work on it as on a normal matrix (array). Here you can see my code:
package MirMir;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Try1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("/Users/Madalin/NetBeansProjects/imp fr/src/com/mkyong/util/Tracker.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext())
{
System.out.print(scanner.next() + "|");
}
scanner.close();
}
}
The program runs perfectly without any errors, just the output I get in the end is: "BUILD SUCCESSFUL (total time: 0 seconds)" and that's all, without any data or anything.
Here is another way for this
public class Tracker {
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f =new File("D:/Tracker.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
String s ;
while ((s=br.readLine())!=null)
{
System.out.println(s);
}
br.close();
}
}
Well this might work ;)
P.S. Change the file location
The code is fine. No problem. I tested it on a sample csv file.
There seems to be some problem with your csv file.
Post a sample from your csv.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
fin.close();
}
}
Around the Scanner portion I cant seem to fix the error.
It says File cant be resolved to a type.
And the file cant be found.
You are missing an import java.io.File; statement. Since you did not import this class (and since your code is not located in the java.io package), Java can't recognize it.
You have a type in your code. You code should be:
FileReader fin = new FileReader(new File("running.txt"));
^^^^^^^^^^^^^^
You can't store instance of File within FileReader.
Also the error that you see is because you have not imported java.io.File, so you need to import File like:
import java.io.File;
A side note: You will need to handle FileNotFoundException.
Try importing java.io.File, and change your FileReader line to the following:
FileReader fin = new FileReader(new File("running.txt"));
It compiled fine for me.
Use the following code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
try{
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
}catch(Exception e){}finally{fin.close();}
}
}
In a part of my university project I have to get a text with some lines then saving it in a string or a string array.My problem is that in scanner class using methods gets only one line of the input. So I cannot get the other lines.please help me.
public class Main {
public static void main(String[] args) {
java.util.Scanner a = new java.util.Scanner(System.in);
String b = "";
while (a.hasNextLine()) {
b += a.nextLine();
}
}
}
You can try to use isEmpty to detect an enter-only input.
UPDATED:
If your input also contain a blank line, then you may specify another terminator character(s); instead of only an empty string.
public class Main {
public static void main(String[] args) {
//for example ",,"; then the scanner will stop when you input ",,"
String TERMINATOR_STRING = ",,"
java.util.Scanner a = new java.util.Scanner(System.in);
StringBuilder b = new StringBuilder();
String strLine;
while (!(strLine = a.nextLine()).equals(TERMINATOR_STRING)) {
b.append(strLine);
}
}
}
If you are building your program from command line, then there's something called "input redirection" which you can use. Here's how it works:
Let's suppose your program is:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (System.in))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
System.out.println ("Total lines: " + lines.size ());
}
}
Now suppose you have input for your program prepared in a file.
To compile the program you'd change the current directory of terminal/command prompt to the program directory and then write:
javac ScanningMultiline.java
And then to run, use input redirection like:
java ScanningMultiline < InputFile.txt
If your InputFile.txt is in another directory, just put its complete path instead like:
java ScanningMultiline < "/Users/Xyz/Desktop/InputFile.txt"
Another Approach
You can try reading your input directly from a file. Here's how that program would be written:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (Paths.get (inputFile)))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
catch (IOException e)
{
e.printStackTrace ();
}
System.out.println ("Total lines: " + lines.size ());
}
}
This approach reads directly from a file and puts the lines from the file in a list of String.
Another Approach
You can read the lines from a file and store them in a list in a single line as well, as the following snippet demonstrates:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ScanningMultiline
{
public static void main (String[] args) throws IOException
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = Files.readAllLines (Paths.get (inputFile));
}
}
Yohanes Khosiawan has answered a different approach so I'm not writing that one here.