Java Scanner File - java

I have a scanner to read a .csv file.
The file is in the same directory and the .java files, however it can't seem to find the file.
What can I do to fix this issue?
Scanner scanner = new Scanner(new File("database.csv"));
Edit: Sorry forgot to mention that I need to use the Scanner package because in the next line I use a delimiter.
Scanner scanner = new Scanner(new File("database.csv"));
scanner.useDelimiter(",|\r|\n");
Also I am working in IntelliJIDEA
So here is the full code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.*;
public class City
{
public String name; // The name of the city
public String cont; // The continent of the city
public int relTime; // Time relative to Hobart (eg. -14 for New York)
public boolean dst; // Does the city use DST?
public boolean valid; // Does the city exist?
Date currDate;
City(){}; // Default constructor
City(String name, String cont, int relTime)
{
this.name = name;
this.cont = cont;
this.relTime = relTime;
valid = verify();
if(valid)
{
currDate = new Date(System.currentTimeMillis() + (3600000 * relTime));
}
}
City(String name, String cont, int relTime, int dstStartDay, int dstEndDay)
{
this.name = name;
this.cont = cont;
this.relTime = relTime;
valid = verify();
if(valid)
{
currDate = new Date(System.currentTimeMillis() + (3600000 * relTime));
// Is DST in effect?
if(currDate.after(new Date(currDate.getYear(), 3, dstStartDay, 2, 0)) &&
currDate.before(new Date(currDate.getYear(), 11, dstEndDay, 2, 0)))
{
// It is... so
relTime--;
}
}
}
private boolean verify()
{
valid = false;
try
{
Scanner scanner = new Scanner(new File("\\src\\database.csv"));
scanner.useDelimiter(",|\r|\n");
while(scanner.hasNext())
{
String curr = scanner.next();
String next = new String();
if(scanner.hasNext())
next = scanner.next();
if(curr.contains(cont) && next.contains(name))
return true;
}
scanner.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
}

As you put the csv file with the source code together, you can't new File directly, you can try,
InputStream resourceAsStream = this.getClass().getResourceAsStream("database.csv");
Scanner scanner = new Scanner(resourceAsStream);
scanner.useDelimiter(",|\r|\n");

When creating or reading a relative file, the path is relative to the specified user.dir. In eclipse, this is often the root of your project.
You can print out the user.dir as follows:
System.out.println(System.getProperty("user.dir"));
This is where the program is looking for the database.csv file. Either add the file to this directory or use an absolute path.

Add the entire path of the file starting from the root folder of the project .
for eg.
Test is my project name in Eclipse. So i should be writing
File csvFile = new File("src\\database.csv");

You should not keep files within the directory that also contain the class files. If you do, you should not access them as a file, but as a resource, and they should be copied to the folder or .jar containing your compiled .class files. If the file is only used by one class in the .jar you should probably be using this.getClass().getResource("database.csv");.
A disadvantage is that you cannot write to resources. If you want to do this I would strongly recommend not to use the source folder for the database file. Instead use a configurable location within the system (e.g. the current working folder).

Related

How to read content of files in directory using java and return the files which have particular keyword

In my code, I am able to list all the files from the folder on my pc but to check whether the keyword is present in those files I used indexOf() in StringBuffer. The problem I am facing is that desired output of filenames having that keyword is not getting printed.
I am not able to find where the error is or what mistake I am making.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
// Creating a File object for directory
File directoryPath = new File("C:\\Users\\nanis\\Downloads\\New folder");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
// System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
for (File file: filesList) {
// System.out.println("File name: "+file.getName());
// System.out.println("File path: "+file.getAbsolutePath());
// System.out.println("Size :"+file.getTotalSpace());
// Instantiating the Scanner class
sc = new Scanner(file);
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
int integer = sb.indexOf("VM"); // the keyword is "VM" that I want to search
if (integer > 0) {
System.out.println("keyword is present in " + file.getAbsolutePath())
}
}
}
}
}
I think the problem is your scanner. You are taking user input input = sc.nextLine(); and to do that you need System.in. Also if I try to print something using sc it prints nothing and that would make while (sc.hasNextLine()) false therefore there is something wrong with your algorithm.
You are doing a search algorithm right? but you are inserting the while loop inside the for each loop. This doesn't work because in the first iteration of the for each loop only the first file is present and so if your search keyword is for the last file it will be false.
A basic search algorithm would be:
1. Input keyword to find
2. Loop through the lists to check if found
3. return either true or false
EDIT: You want to search the .txt files. It is the same concept. You need to store them all first. Not search while storing. If you have stored them you can now search them.
I changed the code to read txt files. Also your directory should only contain .txt files otherwise it will not work because you are reading the content of the files. In your case HashMap would be useful because you need to store two values. File name and the content of it.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
// Creating a File object for directory
File directoryPath = new File("C:\\Users\\nanis\\Downloads\\New folder\\");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
// System.out.println("List of files and directories in the specified
// directory:");
Scanner sc = new Scanner(System.in);
Scanner myReader = null;
HashMap<String, String> fff = new HashMap<String, String>(); // storage for the file name and content
for (File file : filesList) {
File myObj = new File("C:\\Users\\nanis\\Downloads\\New folder\\" + file.getName());
myReader = new Scanner(myObj);
String read = "";
while (myReader.hasNextLine()) {
read += myReader.nextLine();
}
fff.put(file.getName(), read); // store file name and its contents
}
System.out.print("Search The File By Keyword:");
String find = sc.nextLine();
for (String i : fff.keySet()) {
if (fff.get(i).contains(find)) { // check the contents if it contains the keyword u are search for
File found = new File("C:\\Users\\nanis\\Downloads\\New folder\\" + i);
System.out.println("keyword is present in " + found.getAbsolutePath());
}
}
sc.close();
myReader.close();
}
}

How to read a file, included in the package, in Netbeans

I am having difficulty reading a file that I included in a package I am working on for school. The files I need to read, "InputFile1.txt" and InputFile2.txt" are located in a folder called "Lab Exercise 3 Input" in the "Source Packages" folder.
Here is my code for this part:
// create necessary variables
private static ArrayList<String> inputArrayOne = new ArrayList();
private static ArrayList<String> inputArrayTwo = new ArrayList();
private static String nextLine;
private static int currentIndex = 0;
private static int n;
private static int swapCount = 0;
private static String string1;
private static String string2;
/**
* Main method to run
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// assign the files to be read
File inputOne = new File("Lab Exercise 3 Input/InputFile1.txt");
File inputTwo = new File("Lab Exercise 3 Input/InputFile2.txt");
// create a scanner objects to read the files
Scanner sc = new Scanner(inputOne);
Scanner sc2 = new Scanner(inputTwo);
// while loop to iterate through the first file
while(sc.hasNextLine()){
// assign the next line of the file to a string
nextLine = sc.nextLine();
// add that string to an array
inputArrayOne.add(nextLine);
} // end while loop
// close the first scanner
sc.close();
What am I doing wrong? I have tried changing the filename to "InputFile1.txt" without any change. This assignment is due tonight 10/27/17 at 11:59 pm, so any help would be greatly appreciated.
I think you miss / .
File inputOne = new File("/Lab Exercise 3 Input/InputFile1.txt");
File inputTwo = new File("/Lab Exercise 3 Input/InputFile2.txt");
You should put your main method in class as well.
public class Example
{
public static void main(String[] args)
{
}
}
Try getting the current directory and adding that to the File location
String dir = System.getProperty("user.dir");
File inputOne = new File(dir + "\\Lab Exercise 3 Input\\InputFile1.txt");
Edit:
I put a file named InputFile1.txt into a folder named Lab Exercise 3 Input into the Source Packages folder
Then put together a quick bit of code and it worked as expected:
String dir = System.getProperty("user.dir");
ArrayList<String> inputArrayOne = new ArrayList<>();
Scanner sc = new Scanner(new File(dir + "\\Lab Exercise 3 Input\\InputFile1.txt"));
while (sc.hasNext()) {
inputArrayOne.add(sc.nextLine());
}
My only other thought is you saved the file as InputFile1.txt but it's also saved as a .txt file, and therefore is actually
InputFile1.txt.txt
Java knows the concept of resource, a "file" on the class path, together with the .class files, and possible packed in a single application .jar. Hence the path uses slashes (/) and is case-sensitive. Also File cannot be used, as te resource might be packed in a jar. And of course a resource is read-only.
InputStream inputOne = getClass().getResourceAsStream(
"/Lab Exercise 3 Input/InputFile1.txt");
InputStream inputTwo = getClass().getResourceAsStream(
"/Lab Exercise 3 Input/InputFile2.txt");
// create a scanner objects to read the files
Scanner sc = new Scanner(inputOne);
Scanner sc2 = new Scanner(inputTwo);
There also is a Scanner constructor with charset, so you could tell that the file is for instance in "UTF-8".

Remove certain characters from a directory's name in Java

So I wrote a little program to use on a Unix machine that has to get all the names of the files and folders in a directory where it is stored and then remove all the characters from them. These characters (or a character) will be defined by a user. Use case: I put the program in the directory containing various useless files and directories named, for example, "NaCl2!!!!!!!!!", "H2O!", "O2" and "Lithium!!!!!" and I "ask" it to get rid of all the bangs in all the directores' names so it will result in this:
ls
NaCl2 H2O O2 Lithium Unreal3.zip
Ok I guess you get it. So here's the code and it doesn't compile (
DirRename.java:18: error: method renameTo in class File cannot be applied to given types;
tempDir.renameTo(name);
). I guess this error is caused with a substantial problem in my code. Is there a way to get it working, can you tell me, please?
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File tempDir = listOfFiles[i];
name = tempDir.getName().replaceAll(annoyngChar, "");
tempDir.renameTo(name);
}
}
}
}
Need to say, the program is unfinished, I am sorry for that.
File.renameTo(File dest) takes a File parameter, not a String. So, you need to create a File instance with the correct path (using the new name), and pass that instance to renameTo.
Try this (not tested):
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File f = listOfFiles[i];
String oldName = f.getName();
name = oldName.replaceAll(annoyngChar, "");
if (!oldName.equals(name)) {
File newF = new File(dir, name);
f.renameTo(newF);
}
}
}
}
}
Alternatively, you can use Files.move to rename the file. The documentation has an example of how to rename a file while keeping it in the same directory.

Search a directory for a .txt file, without needing full pathname. - Java

I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time. This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;
public class FileHandler {
public static boolean fileCheck = true;
public static File logFile;
public static PrintWriter logPrinter;
public static PrintWriter handMadeFile;
public static LocalDate date = LocalDate.now();
public static File fileFromScanner;
public static File directory = new File("/Users/mizu/homework");
public static String fileName;
public static File file;
public static String created = "Log has been created.";
public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
public static String mainFileName = "/Users/mizu/homework/main_file.txt";
public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
public static String fileMessage = "I just wrote my own file contents.";
public static void main(String[] args) {
if (!directory.exists())
{
// create new directory called homework
directory.mkdir();
}
// gets file request from user
System.out.print("Enter file to find: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
// initialize the main_file
fileFromScanner = new File(mainFileName);
// if main_file exists or not, print message to my_log
if (!fileFromScanner.exists())
{
// create my_log file (logFile), to keep track of events
writeToLog(created);
writeToLog("File path you entered: "
+ fileName + " does not exist.");
System.out.println(fileName + " - does not exist.");
// create file since it doesn't exist
File mainFile = new File(mainFileName);
try {
PrintWriter pwMain = new PrintWriter(new BufferedWriter
(new FileWriter(mainFile)));
writeToLog("Created " + mainFileName);
pwMain.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
writeToLog(fileName + " already exists.");
System.out.println(fileName + " - already exists.");
}
// use writeToFile method to write file, create new file name
FileHandler testFile = new FileHandler(fileFromMethod);
testFile.writeToFile(testFile, fileMessage);
} // end Main
All of the other methods are below here, but not shown to keep it short.
As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
// Get the absolute path from where your application has initialized
File workingDirectory = new File(System.getProperty("user.dir"));
// Get user input
String query = new Scanner(System.in).next();
// Perform a search in the working directory
List<File> files = search(workingDirectory, query);
// Check if there are no matching files
if (files.isEmpty()) {
System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
+ query + "'");
return;
}
// print all the files that matched the query
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
public static List<File> search(File file, String query) {
List<File> fileList = new ArrayList<File>();
// Get all the files in this directory
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
// use recursion to search in all directories for the file
fileList.addAll(search(f, query));
} else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
// if the filename matches the query, add it to the list
fileList.add(f);
}
}
}
return fileList;
}
1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.

Reasons why .txt file could not be found?

When I run this program, it cannot find the files I direct it to. I put the two text files into the src folder of the program, and to my understanding all I would have to do to call it is File f = new File("filename.txt"). But that doesn't work. I also tried using the exact directory inside of File() but it doesn't work either. The files just contain a name and an amount of money beside them. Any ideas?
import java.io.*;
import java.util.Scanner;
class Donors {
File donor2;
File donor3;
Scanner inD2;
Scanner inD3;
Donors(File d2, File d3){
donor2 = d2;
donor3 = d3;
}
double totalDonations(){
double total = 0;
try{
inD2 = new Scanner(donor2);
while(inD2.hasNext()){
total += inD2.nextDouble();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File can't be found");
}
try{
inD3 = new Scanner(donor3);
while(inD3.hasNext()){
total += inD3.nextDouble();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File can't be found");
}
return total;
}
public void closeFile(){
inD2.close();
inD3.close();
}
}
public class DonorCalculations {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int userInput;
File donor2 = new File("H:\\CSC 191\\Assignment9\\src\\resources\\donor2.txt");
File donor3 = new File("donor3.txt");
Donors dObj = new Donors(donor2, donor3);
do{
System.out.println("SELECT");
System.out.println("1. Total money from donations");
System.out.println("2. Total donation from a individual");
System.out.println("0. Quit");
userInput = input.nextInt();
System.out.println();
switch(userInput){
case 1:
System.out.println(dObj.totalDonations());
break;
case 2:
System.out.println("Enter donor's name: ");
String name = input.next();
//dObj.donorTotal(name);
break;
case 0:
System.out.println("Goodbye!");
break;
}
System.out.println();
}while(userInput != 0);
}
}
You've now embedded the files into your application making them embedded resources. You can no longer access them as if they were files.
Instead you need to use the resource lookup functionality Java provides, for example...
InputStream donor2 = getClass().getResourceAsStream("/resources/donor2.txt");
This may or may not be a good thing.
If you must read the contents from flat files, then those files need to be located within a relative location of the execution context of the program.
You can determine the execution context of your current program by using System.out.println(System.getProperty("user.dir"));, which will print the current directory that the program is executing within. Your text files should be located within a relative context of this directory while you're developing.
When it's built, the files will need to be within the same relative context as the program is been executed from
Change:
File donor2 = new File("H:\\CSC 191\\Assignment9\\src\\resources\\donor2.txt");
File donor3 = new File("donor3.txt");
Donors dObj = new Donors(donor2, donor3);
To:
File donor2 = new File("H:\\CSC 191\\Assignment9\\src\\resources\\donor2.txt");
File donor3 = new File(getClass().getClassLoader().getResource("donor3.txt"));
Donors dObj = new Donors(donor2, donor3);

Categories