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".
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();
}
}
This one's a fun one. I'd appreciate any bit of help, and no previous stackoverflow questions are pointing me in the right location. Docs also weren't very helpful to me.
I'm being thrown a FileNotFoundException with this block of code:
public static int wordOccurance(Word t, File D) throws FileNotFoundException
{
int occurance = 0;
BufferedReader mainReader = new BufferedReader(new FileReader(D));
Scanner kb = new Scanner(mainReader);
My tester file does not cause this to occur: ie. "File tester = new File("C:\read.txt");"
But the problem occurs solely when I pass a File constructed by this method:
public static File makeAndCombineFile(String FileOne, String FileTwo) throws IOException
{
BufferedReader mainReader = null;// null holder value for the later useful bufferedReader
Scanner kb = null;// null holder for later useful Scanner
StringBuilder sb = new StringBuilder();
OTHER CONDITIONS BETWEEN THESE TWO CHUNKS. MOST LIKELY NOT PERTINENT. ALSO RETURN FILE, JUST IF ONE INPUT IS NULL.
else //in case both are good to go and obviously not null
{
mainReader = new BufferedReader(new FileReader(FileOne));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine() + "\n");
mainReader = new BufferedReader(new FileReader(FileTwo));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine()+ "\n");
kb.close();
return new File(sb.toString());
}
}
It took me a while to figure out what was going on here, but it looks to me like you think that this line:
return new File(sb.toString());
creates a file on disk containing the text read from the two scanners. It does not. It creates a java.io.File, which is basically a representation of a file path; the path represented by this File is the data read from the scanners. In other words, if FileOne and FileTwo contained the text to War and Peace, then the path represented by that file would be the the text of War and Peace. The file will not have been created on disk; no data will have been written to it. You've just created an object that refers to a file that does not exist.
Use a FileWriter, perhaps in conjunction with a PrintWriter, to save the lines of text into a file; then you can create a File object containing the name of that file and pass it to your other routine:
PrintWriter pw = new PrintWriter(new FileWriter("somename.txt"));
while(kb.hasNext())
pw.println(kb.nextLine());
pw.close();
return new File("somename.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).
So I'm trying to read a file using the Scanner, however, all the contents of the file are wiped, and then it reads nothing. Here are the methods I've ran in succession, in my Main method:
private static Scanner x;
private static Formatter y;
public void openMainFile(String name){
try{
x = new Scanner(new File("main.mcmm");
y = new Formatter("main.mcmm");
}catch(Exception e){
GUI.error(2);
}
}
This method runs perfectly fine
public void readModMainFile(){
while(x.hasNext()){
Main.name = x.next();
Main.ver = x.nextFloat();
Main.base = x.nextBoolean();
Main.dev = x.next();
Main.date = x.next();
}
}
After this method runs, the file is empty, and the 'Main.-' variables don't have any values.
Don't open the same file for reading and writing at the same time. Write into a temporary file first, then rename it. Alternatively, you can read the whole file first, store everything, close the Scanner and then you can overwrite the file.
Your Formatter is truncating the output file every time. From your comments in this post, you indicate that the number of variables will remain constant. You could use a temporary file to achieve this (+1 to #biziclop):
File inputFile = new File("main.mcmm");
Scanner scanner = new Scanner(inputFile);
File tempFile = File.createTempFile("main.mcmm",".temp");
Formatter y = new Formatter(tempFile);
y.format("%s", name);
// more reading & formatting, etc.
y.close();
scanner.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Remember to close both the Scanner and Formatter so that the input & output files can be deleted & renamed respectively.
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.