Output the strings inside of multiple .txt files in a directory - java

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.

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".

Have java find/read a file from user input?

The program must print the text in file I ask it to read.
The problem is I coded it to read the text from a specific file
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
How do I get the program to read the text from a file specified by user input?
*The file is going to be in the same directory/folder as the program so that's not an issue.
EDIT: My prior attempt at user input
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Declare a String variable, such as someUserFile, take user input. Then...
File file = new File(someUserFile);
Scanner inputFile = new Scanner(file);
You may want to check their input and append ".txt" to the end of their input.
If this works:
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Then this:
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Will do the exact same thing assuming you type numbersonnumbers.txt and type that exactly.
Assuming you type numbersonnumbers.txt exactly, the second snippet does the EXACT same thing as the first snippet.
Firstly you should ask the user the input the filename. Then just replace the "numbersonnumbers.txt" in your code to the variable that you set for the user input.
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
1) The program must print the text in file:
Lets call this file, dataFile.text, or dataFile.dat (either way works)
Assuming that the client will be inputing any file, we must get the file's name...
These Java statements will do the trick:
// Create a Scanner to read user's file name
Scanner userInput = new Scanner(System.in);
// Request the file name from client
System.out.println("Enter name of input file: ");
// Gets client's file name
String fileName = scanFile.nextLine();
// scanFile, scans the new File fileName (client's file), which is located in the src directory. The "src/" represents the path to the file (client's file).
Scanner scanFile = new Scanner(new File("src/" + fileName));
Since the problem states the file, "will be located in the same directory as the program," its not an issue.
---------------------------------------------------------------------------------
2) The problem is I coded it to read the text from a specific file
Yes, all you did was create file of your own called, "numbersonnumbers.txt," this is exactly the code you should be following in the solution to this problem, but instead of typing "numbersonnumbers.text", you will be using the client's input file, which is the String variable "fileName" in the previous code...*
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Corrected: File file = new File("src/" + fileName);
Scanner inputFile = new Scanner(file); // Will scan all the file's data
Corrected More: Scanner inputFile = new Scanner(new File("src/" + fileName));
---------------------------------------------------------------------------------
3) The program must print the text in file
Now to print the data items in the file to the console you simply, copy every item in the file, to an array, list, or tree depending on specifications of implementation, but this is obviously begininer programming so, never mind lists and trees, use an array.
So you have completed upto either Scanner scanFile in #1 or Scanner inputFile in #2
Now, create an array, obviously the type of array would be based on the type of data items in the file... Strings for (e.g., month names) or int for (e.g., ID numbers .. ect)
Assuming the data items in the file are names of months (jan, feb, march) we will make an array of type String.
String[] fileData = new String[100]; // has random length (100)
// Now we will be copying every item from the file into the array, you will need place holder value to keep track of the position during the traversal (stopping at every item) of the file's items.
int i = 0; // itialize the start of the traversal (index 0 of the file items)
while (scanFile.hasNextLine()) { // While file has input on next line, read from file.
fileData[++i] = scanFile.nextLine(); // Input file data and increment i
System.out.println(fileData[i]); // Prints all of the file's data items
} // end while
Respectfully,
-!di0m
You got almost everything you need in your code already. You just need to re-arrange your lines of code properly, and add couple more.
you need two steps: scan what the user enters as full file path, then scan the actual file data as follows:
// Scanner Object to be used for the user file path input
Scanner keyboard = new Scanner(System.in);
// Asks the user to enter the full path of their file
System.out.print("Enter your full file path: ");
// Stores the user input file path as a string
String filename = keyboard.nextLine();
// Creates a File object for the file path, and scans it
Scanner inputFile = new Scanner(new File(filename);
Now you can read the scanned File inputFile. For example you can use a while loop to read one line at a time to read all data and print it out as follows:
// Reads one line at a time, and prints it out
while(inputFile.hasNext) {
System.out.println(inputFile.nextLine());
Or you can put each line's raw data (trimmed and split) in an array and print out each line as an array as follows:
// Declares a String array[] to be used for each line
String[] rawData;
// Reads one line at a time, trims and split the raw data,
// and fills up the array with raw data elements, then prints
// out the array. it repeats the same thing for each line.
while (scanner2.hasNext()) {
rawData = scanner2.nextLine().trim().split("\\s+");
System.out.println(Arrays.toString(rawData));
}

File contents are wiped when trying to read from Scanner

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.

Retrieving and Replacing number in text file

I need to retrieve and change a number in a text file that will be in the first line. It will change lengths such as "4", "120", "78" to represent the data entries held in the text file.
If you need to change the length of the first line then you are going to have to read the entire file and write it again. I'd recommend writing to a new file first and then renaming the file once you are sure it is written correctly to avoid data loss if the program crashes halfway through the operation.
This will read from MyTextFile.txt and grab the first number change it and then write that new number and the rest of the file into a temporary file. Then it will delete the original file and rename the temporary file to the original file's name (aka MyTextFile.txt in this example). I wasn't sure exactly what that number should change to so I arbitrarily made it 42. If you explain what data entries the file contains I could help you more. Hopefully this will help you some anyways.
import java.util.Scanner;
import java.io.*;
public class ModifyFile {
public static void main(String args[]) throws Exception {
File input = new File("MyTextFile.txt");
File temp = new File("temp.txt");
Scanner sc = new Scanner(input); //Reads from input
PrintWriter pw = new PrintWriter(temp); //Writes to temp file
//Grab and change the int
int i = sc.nextInt();
i = 42;
//Print the int and the rest of the orginal file into the temp
pw.print(i);
while(sc.hasNextLine())
pw.println(sc.nextLine());
sc.close();
pw.close();
//Delete orginal file and rename the temp to the orginal file name
input.delete();
temp.renameTo(input);
}
}

Categories