Error on finding file and on the New File location - java

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

Related

FileReader in Java not finding the file

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:

Binary file is not saving if length of string is not same

I am trying to save text and int value in a binary file but it is not working as expected.
This is my code.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FilterOutputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class Test{
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner input=new Scanner(System.in);
System.out.println("Enter first name of doctor : ");
String fn=input.next();
System.out.println("enter middle name of doctor : ");
String mn=input.next();
FileOutputStream os=new FileOutputStream("Doctorsdata.txt");
DataOutputStream file=new DataOutputStream(os);
file.writeUTF(fn.trim());
file.writeUTF(mn.trim());
FileInputStream osb=new FileInputStream("Doctorsdata.txt");
DataInputStream osa=new DataInputStream(osb);
System.out.println("a "+osa.readUTF());
System.out.println("b "+osa.readUTF());
file.close();
}
}
This is my input
fn mn Output
abc def ̀a扡c搃晥
abc defg abc defg
If i write fn and mn as of same length it will work and if they are of not same length it will not work like above. Also if I have a 3rd variable of type byte and i will write like file.writeByte(age); in first input's case it will not work.
What am I doing wrong?
Thanks.

Paths.get doesnt find file Windows 10 (java)

I'm following some course on udemy . Im learning about Paths , but i cant get Paths.get to work.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path filePath = Paths.get("C:\\OutThere.txt");
printFile(filePath);
}
private static void printFile(Path path){
try(BufferedReader fileReader = Files.newBufferedReader(path)){
String line;
while((line = fileReader.readLine())!=null){
System.out.println(line);
}
}catch(IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
The File exists , the name is correct and its on the C drive. What am i doing wrong?
java.nio.file.NoSuchFileException: C:\OutThere.txt
at com.bennydelathouwer.Main.main(Main.java:16)
It's a bad practice to hard-code "/" or "\" use:
File.separator
++ are you sure you have the proper privileges to read this file?

Throws FileNotFoundException when creating scanner from file

I'm trying to show a file open dialog and then create a scanner to read the selected file. When I run my code it throws a FileNotFoundException which doesn't make sense to me since it throws the exception before it opens the file selector window.
package files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main (String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI () {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
System.out.println(file.exists());
Scanner fromFile = new Scanner(file);
}
}
Starting with your example code...
import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI() {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
System.out.println(file.exists());
Scanner fromFile = new Scanner(file);
}
}
You are getting a compiler error because Scanner(File) can throw a FileNotFoundException
You either need to catch the exception or re-throw it, for example...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI() {
JFileChooser chooser = new JFileChooser();
switch (chooser.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = chooser.getSelectedFile();
System.out.println(file.exists());
try (Scanner fromFile = new Scanner(file)) {
while (fromFile.hasNextLine()) {
String text = fromFile.nextLine();
System.out.println(text);
}
} catch (FileNotFoundException exp) {
exp.printStackTrace();
}
break;
}
}
}
You might also like to have a look at How to Use File Choosers and make sure you are checking the return result of showOpenDialog so you know how the dialog was closed
Also, have a look at The try-with-resources Statement for more details about how to manage your resources
I think your code is somewhat as follows :
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;
public class Solutiokn {
public static void main(String[] args) {
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(null);
File file = fileChoose.getSelectedFile();
System.out.println(file.exists());
try {
Scanner fromFile = new Scanner(file);
while(fromFile.hasNextLine())
System.out.println(fromFile.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Ok now this works just fine. Only point when I have issue is when I do not pick a file in the file chosser and just click cancel. When this happens the scanner itself is not created as value in "file" is null. I suggest adding a check manually to see if any file was selected or not like if(file==null) System.out.println("Please select a file"); or throw your own exception. If you don't probably a sudden nullPointerException will pop up.
Edit : As madProgrammer pointed out file.getName() would rather instead throw nullPointerException I tried changing it to file.exists() that still throws Exception if file was not selected. So instead maybe checking file==null is better. file.exists() checks if file denoted by this pathname exists but if we never inititalized it i.e just cancelled in file chooser then it does not help.

Searching a CSV file Java

Im trying to a specific String of number in a csv file and I keep getting an a FileNotFound exception even though the files exists. I cant seem to fix the problem
Sample Csv file
12141895, LM051
12148963, Lm402
12418954, Lm876
User Input : 12141895
Desired Result : True
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.List;
public class tester
{
public static void main (String [] args ) throws IOException
{
boolean cool = checkValidID();
System.out.println(cool);
}
public static boolean checkValidID() throws IOException
{
boolean results = false;
Scanner scan = new Scanner(new File("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\IDandCourse.csv"));
String s;
int indexfound=-1;
String words[] = new String[500];
String word = JOptionPane.showInputDialog("Enter your student ID");
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
if (indexfound>-1)
{
results = true;
}
else
{
results = true;
}
return results;
}
}
use:
import java.io.File;
import java.io.FileNotFoundException;
Also, in your function declaration try using
public static boolean checkValidID() throws FileNotFoundException
and likewise with the main function.
If the file is present and named correctly, this should handle it.

Categories