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);
Related
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();
}
}
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.
i am having an issue opening a file and getting my program to read the integers in the file. In the code below, to get my car data i can either have it randomly generated to get my duration time for a car, and the chance that a car arrives. Or read integers from a file. The file is already given by our professor and her is what is in the file:
37259 9819
46363 22666
46161 79934
5693 31416
91459 8272
72792 9493
83603 8372
77842 64629
84792 747
1299 178
Apparently I am unable to open the file even using the absolute path, or data = dataFile.nextInt() isn't the correct format to use. Any help would be appreciated i am absolutely stumped on this part, my whole program works but files are my Achilles heel.
if (dataSource == 1) {
System.out.printf("Enter a filename \t :");
String aName = input.next();
java.io.File file = new java.io.File(aName);
try {
dataFile = new Scanner(file);
} catch (Exception e) {
System.out.println("Can't open file");
}
} else {
dataRandom = new Random();
System.out.println("Is Random Active");
}
input.close();
}
private void getCarData() {
if (dataSource == 1) {
int data1;
int data2;
data1 = dataFile.nextInt();
data2 = dataFile.nextInt();
anyNewArrival = (((data1%100) + 1) <= chancesOfArrival);
serviceDuration = (data2%maxDuration) + 1;
System.out.println("New Car has arrived with Duration Time: " + serviceDuration);//}
}
If running from Netbeans or Ecplise, you can use the relative path "text.txt" And make sure your file structure is something like this
ProjectRoot
src
build
text.txt
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).
I have a folder which file name is: "List of names". Inside that folder i have a 5 ".txt" file documents and each document file names is a person's name.
I want to retrieve the five documents and display the strings inside each documents. How do i do this? I tried this:
import java.io.*;
import java.util.*;
public class Liarliar {
public static void main(String args[])throws IOException{
File Galileo = new File("C:\\List of names\\Galileo.txt");
File Leonardo = new File("C:\\List of names\\Leonardo.txt");
File Rafael = new File("C:\\List of names\\Rafael.txt");
File Donatello = new File("C:\\List of names\\Donatello.txt");
File Michael = new File("C:\\List of names\\Michael.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try{
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
}catch(FileNotFoundException e){
}catch(IOException e){
}
}
}
Thanks in advance for someones time...
It would be more generic to not hard code the names of the individual files like Galileo.txt. You can create a File representing the directory, and then call listFiles to get all the files in the directory, like
File nameFile = new File(""C:\\List of names");
File[] personFiles = nameFile.listFiles();
Then you can iterate over this File array, and open each file in turn, and read the contents, like
for (File person : personFiles) {
showFileDetails(person);
}
where showFileDetails is a separate method you write for opening the file and displaying the information.
the following lines are not needed as they are meant to take input from user.
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
Instead you need to read the files one by one using a FileInputStream or FileReader. See here for an example on how to read data from files. Do this for each of your files.