I am trying to use the values from a text file in my program, but first I would like to really understand how to use JFileChooser which I cannot make it work.
The program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Hw7Problem2 {
public static void main(String[] args) throws FileNotFoundException {
JFileChooser student_scores = new JFileChooser();
int jfcUserOption = student_scores.showOpenDialog(null);
// To verify it reads
if (jfcUserOption == JFileChooser.APPROVE_OPTION) {
File chosenFile = student_scores.getSelectedFile();
System.out.println("The file you chose was: " + chosenFile.getName());
}
Scanner scanner = new Scanner(new File("student_scores.txt"));
// Print text file on program
System.out.println(scanner);
}
}
The error:
The file you chose was: student_scores.txt
Exception in thread "main" java.io.FileNotFoundException: student_scores.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Hw7Problem2.main(Hw7Problem2.java:21)
You are doing this correctly until you create the scanner. The problem is that you aren't using the result of the JFileChooser. It looks like you put the result in chosenFile. getSelectedFile() will return the file that was chosen, so you just need to create the scanner with it.
If you need to understand more about how the JFileChooser works, you can find the documentation online here.
Related
I'm trying to read from a file using the Scanner and File class:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TextFileReaderV1
{
public static void main(String[] args) throws IOException
{
String token = "";
File fileName = new File("data1.txt");
Scanner inFile = new Scanner(fileName);
while( inFile.hasNext() )
{
token = inFile.next( );
System.out.println(token);
}
inFile.close();
}
}
However, it is saying, "no such file or directory". and giving me the "java.io.FileNotFoundException"
I am using IntelliJ IDEA and the file is in the current directory I am working in: src/data1.txt -> next to GetFile.java (current code)
Full Error Message:
Exception in thread "main" java.io.FileNotFoundException: data1.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at GetFile.main(GetFile.java:19)
**Edit: ** It has been solved!! The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
Try entering the full path of the file. If that works, you can either be done at that point or look into relative file paths.
So I'm writing a piece of code that reads in many addresses and then manipulates the data, line by line, then adds it to a Binary Search Tree. However, the file isn't being found no matter what I try. I know the txt file needs to be in the root directory, but (I'm a student) we're required to submit a .tar.gz containing the contents of a directory made specifically for the assignment so I suppose it needs to be in the submitted folder.
I've tried using the "normal" methods I used in IDEs, but they all return the same error.
My code (roughly - obviously you don't really need to see the BST/manipulation stuff), right now, but I've tried every other typical file read-in method:
import java.io.InputStream;
import java.io.*;
import java.util.Scanner;
public class PrintIt{
public static void main(String args[]){
try{
File inFile = new File("/bin/testdata.txt");
Scanner sc = new Scanner(inFile);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line); //manipulation in place of this
}
sc.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
I really only need the reading in the file part - the BST stuff/manipulation is just for context, just in case it mattered/there's a better way than reading through each line of the file and adding each to the Tree.
So I've been looking around to solve my problem but I am only finding part of the solution and I'm trying to modify those solutions to suit my needs but I am not able to do so.
I'm using this class to check for file type..
package parser;
import java.io.File;
import java.io.FilenameFilter;
//import java.util.Scanner;
public class FileFilter {
public File[] finder(String dirName){
File dir = new File(dirName);
//#SuppressWarnings("resource")
//Scanner scanner = new Scanner(System.in);
//System.out.println("Enter a file name: ");
//System.out.flush();
//String name = scanner.nextLine();
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return fileName.endsWith(".xls");
}
});
}
}
And here's the beginning of my main class that I'm trying to work with (where I ask the user to type in just the file name (without the extension). And this is where I want it to call that FileFilter class and see if the file name typed has the "xls" file extension or not and if not then throw an exception and terminate, if it checks out then continue on...
package parser;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.log4j.Logger;
public class ReadExcel {
static final String ExcelFilePath = "D:\\eclipse\\workspace\\Assesment project\\";
static final String RatesPropFilePath = "D:\\eclipse\\workspace\\Assesment project\\rates.properties";
static final String TotalCostLogFilePath = "D:\\eclipse\\workspace\\Assesment project\\Total_Cost_Log.txt";
static final int SheetNum = 0;
static final int CellLookUp = 2;
static final String AvoidText = "CC";
static final Logger logger = Logger.getLogger(ReadExcel.class);
#SuppressWarnings("static-access")
public static void main(String[] args) {
// Find all Excel files in folder
/*FileFilter fileSearch = new FileFilter();
System.out.println("Enter a file name: ");
System.out.flush();
String name = fileSearch.*/ // I'm stuck here, and I cannot find a way to fix it.. :S
// Create an object of File class that points to the Excel file
File excel = new File(ExcelFilePath);
EDIT: To clear the confusion, what I'm trying to do is: I'm trying to make the user to input the file name only (minus the extension). Then when the user enters the file name it then uses the FileFilter class to check if the file name (entered by the user) has the extension defined by the FileFilter (which is xls).. If so, then continue the program (using that file).. If not then throw an error and then terminate. I hope this makes it clearer.. :S
Does not seem too hard, let's see (comments inside!)
public static void main(String[] args) {
// create a FileFilter
FileFilter ff = new FileFilter();
// use finder method to get array of Files
File[] files = ff.finder(yourFolder);
// if files is empty
if (files == null || files.length == 0) {
// throw or print the error
} else {
// iterate over all found files:
for (File f : files) {
// f is pointing to excel file
}
}
}
UPDATE:
According your comment:
the problem is asking the user for file name then by using the FileFilter class and if it has the extension defined by that class then continue.. if not then throw exception and break.
Well... to ask for file extension, you must do more modifications:
First modify FileFilter to accept it:
public File[] finder(String dirName, String filename){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// check for exact filename:
return name.equals(filename + ".xls");
// use both parameters to check various files with filename pattern
return name.endsWith(".xls") && name.startsWith(filename);
}
});
}
Second use a Scanner to get the extension and use it in the FileFilter call:
System.out.println("Enter file extension: ");
Scanner scanner = new Scanner(System.in);
String extension = scanner.nextLine();
Finally, in your Main method, make the call with this extension and folder:
public static void main(String[] args) {
// create a FileFilter
FileFilter ff = new FileFilter();
// ask for extension
System.out.println("Enter file name: ");
Scanner scanner = new Scanner(System.in);
String filename= scanner.nextLine();
// use finder method to get array of Files
File[] files = ff.finder(yourFolder, filename);
// if files is empty
if (files == null || files.length == 0) {
// throw the error
} else {
// iterate over all found files:
for (File f : files) {
// f is pointing to excel file
}
}
}
What are you stuck on?
Getting the file name from the user (at the console)
This is a question of it's own but luckily it's been answered many times on StackOverflow (such as here) and other places, using other methods (such as here). Personally I prefer the second one...
System.out.println("What is the name of the file: ");
Scanner in = new Scanner(System.in);
fileNameInQuestion = in.nextLine();
This is already present in your code but is commented out in FileFinder
Verifying the file exists
Create an instance of your "Filter", have it search for the given file name using the method you have already then throw an exception if it's not found.
//Create instance of your "Filter"
FileFilter fileSearch = new FileFilter();
/**
* Get the name of and search for the filename in question
* in the 'directoryToSearch'
*/
File[] file = fileSearch.finder(directoryToSearch);
//If no file is found then throw an Exception
if (file == null || file.length == 0)
{
throw new Exception();
}
//...continue on...
Note that file (see File.listFiles()) can be null here if the argument directoryToSearch is not a directory or can have a length of 0 if no files are matching. Either of these mean there is a problem finding the file so I throw an exception if one or (||) the other is true.
Note about exceptions
This isn't generally considered proper use of exceptions though. Mainly because they are supposed to represent exceptional circumstances. In this case it's more likely you would want to have some validation and feedback of the filename rather than an exception on invalid input, see here.
For this small case though it's not really a big deal, just something to be aware of.
I am writing a program for my comp sci class, andI keep getting the same error.
Exception in thread "main" java.io.FileNotFoundException: data.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at Search.main(Search.java:18)
Here is the beginning of my code:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.IOException;
public class Search{
public static void main(String[] args)throws IOException{
Scanner inData = new Scanner(new File("data.txt"));
String data=inData.nextLine();
String[] arr = data.split(" ");
while(inData.hasNext()){
String search=inData.nextLine();
int len=search.length();
ArrayList<String> result = new ArrayList<String>();
I have a text file in the same Java Project, so I'm not sure what the problem is and I've tried moving the location of the file around but nothing is working.
The working path of your executed code can be determined with this code:
System.out.println(new File(".").getAbsolutePath());
Usually this is the target or the classes or the bin folder, depending on your IDE.
You have to put the file data.txt in the root of your eclipse java project , outside your folder /src/.
So there is the code:
public class Main{
public static void main(String[] argv) throws IOException{
new Main().run();
}
PrintWriter pw;
Scanner sc;
public void run() throws IOException{
sc = new Scanner(new File("input.txt"));
int a=sc.nextInt();
pw = new PrintWriter(new File("output.txt"));
pw.print(a*a);
pw.close();
}
}
Error:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Main.run(Main.java:14)
at Main.main(Main.java:8)
Like i understand it can't find file named input.txt, BUT! I have that file in same directory where Main class is, what can be the promblem then?
p.s Tried on cmd and eclipse, both give same error.
it is not relative to your Main class, it is relative from where you launch this Java program (i.e. current work directory)
it is relative to
System.getProperty("user.dir")
You probably need to specify the PATH to your file, one thing you can do is test for existence and readability with File.canRead() like
File file = new File("input.txt");
if (!file.canRead()) {
System.err.println(file.getCanonicalPath() + ": cannot be read");
return;
}
An example using a PATH might be (for Windows) -
File file = new File("c:/mydir/input.txt");
You can use System.out.println(System.getProperty("user.dir")) to see where Java is looking for the file by default. This is most likely your project folder. This is were you have to put the file if you don't want to specify an absolute path.