I'm required to take a file name as input for a scanner in one method and use that scanner as reference to the file path for the rest of my code in all other methods.
I'm learning file i/o, and for this project I'm supposed to take a file name as input, count the number of lines in the file and put each line into an array.
My issue comes in during the FileUtils.countRecords method. After returning a file type in FileUtils.openInputFile and then taking that data and putting it into a scanner (variables inf and fin in the code) I'm supposed to take that scanner and use it to point to a file again. (File input=new File(scanner))
*My instructor gave us a hint that "The Scanner is at the EOF and will need to be reset" though I haven't been able to find any 'end of file' documentation that would help me here.
From main method (!this can not be changed!)
File inf = null;
int total, choice;
String [] words = null;
Scanner kb = new Scanner(System.in), fin = null;
inf = FileUtils.openInputFile(kb);
fin = new Scanner(inf);
total = FileUtils.countRecords(fin, 1);
fin.close();
FileUtils.openInputFile(kb) returns the type File after being given the file's path.
public static int countRecords(java.util.Scanner fin,int linesPer)
{
File input = new File(fin.toString()); //fileNotFoundException here
File input = new File(fin); //also throws filenotfoundexception
When I try System.out.print(fin) or System.out.print(fin.toString()) I get this:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
Which is obviously not a file name or path. I'm wondering if I need to convert my scanner into something else before assigning my file variable to it. Or if there is something like .toString() that would turn the above scanner properties into readable text. Or how to "reset the scanner at the eof."
So I guess the scanner fin doesn't hold the path/file name. It is a reference to the open file itself, therefore all I needed to do was count each line from the file like so:
while(fin.hasNext())
{
fin.nextLine();
count ++;
}
Related
Please note, this is a homework assignment.
Can anybody help me figure out how to append text to the beginning of every line of a text file? This is what I have so far:
package addStr;
import java.util.*;
import java.io.*;
public class AddStr {
public static void main(String args[]) throws FileNotFoundException, IOException{
Scanner con = new Scanner(System.in);
System.out.print("Enter input file: ");
String fileIn = con.next();
System.out.print("Enter output file: ");
String fileOut = con.next();
File in = new File(fileIn);
Scanner sc = new Scanner(in);
FileWriter out = new FileWriter(in, true);
PrintWriter print = new PrintWriter(out);
print.print("hello");
print.close();
}
}
I only printed "hello" as a test to see where in the file it would append. It appends at the end of the very last line. I need it to append to the beginning of the first line, and then use a loop to append it to the beginning of each subsequent line.
Also, the program prompts the user to input the file name.
The simplest way to change the content of a file is to open it for reading, read it into a structure, re-open the file for writing then write from the structure back to file. Unless the file is large then the performance will be perfectly acceptable.
If you are using Java 8 then this can be quite trivial. Assuming you have a Path to the file:
List<String> lines = Files.lines(path).map(s -> "Prefix" + s).collect(Collectors.toList());
Files.write(path, lines);
I am trying to open whose name is written into the console. I can't seem to resolve the type mismatch. Any help would be appreciated.
Scanner inputFileName = new Scanner(System.in);
File file = new File (inputFileName);
Use something like this: String name = inputFileName.nextLine(). So when you call nextLine() you are reading the rest of this first line.
In your code, you are not getting any input from the user.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
In your case, your inputFileName is only a Scanner object which you can use it to prompt for user input. It is not your filename nor is it prompting for any input at the moment.
You may use inputFileName.nextLine() to prompt user for input first:
Scanner inputFileName = new Scanner(System.in); //Create Scanner object
String fileName = inputFileName.nextLine(); //Store user's input in fileName
File file = new File (fileName); //Create File object with fileName
Using java, I need to make a program that asks the user which file to scan, and to do some work with the data in the file.
My program is supposed to select a file, scan the file for a specific character that the user specifies, and return with how many specific characters there are in that file.
This is my code so far:
import java.io.*;
import java.util.Scanner;
public class CharSearch {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file you want to search.");
String fileInput = scanner.nextLine();
System.out.println("What character would you like to look for in " + fileInput + "?");
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner);
}
}
I imported io and scanner, then set up the scanner to read which file the user inputs. I print back out that file name. The last two lines are where I need help. How can I make the scanner return with the data in the file.
There is a file in my folder called data.txt and all that is written in it is "dataWord." For starters, I want the scanner to read the file and the program to display dataWord, but its not working. I am a rookie, so please work with me. Thanks.
Instead of passing path of file as String pass it as a File
Scanner fileScanner = new Scanner(new File(fileInput));
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
scanner.close();
fileScanner.close();
If the file is an external file or not in your project, you can specify the absolute path of file.
If it is in classpath you can read using ClassLoader
java.io.InputStream inputStream = this.getClassLoader().getResourceAsStream("file_path")
Scanner has a constructor with InputStream
I have a piece of code I'm currently struggling with
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
Basically, let's say I have a file called text.txt and I enter that as user input for the scanner to analyze, where should it be placed in my directory? I tried to put it in the bin and src files of my class and inside my class also but I keep getting a FileNotFoundException at the line:
Scanner input = new Scanner(new File(files));
It doesn't even ask me for any user input.
With
String current = System.getProperty("user.dir");
you can check where you are currently in.
You might try just putting it in the project root folder, one above src/bin.
I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
System.out.println("Enter your file name");
String name = "";
kb.nextLine();
name = kb.nextLine();
File file = new File(name);
return file;
}
The scanner I passed into it is:
Scanner fin = null, kb = new Scanner(System.in);
File inf = null;
inf = FileUtil.readFileInfo(kb);
fin = new Scanner(inf);
You're reading from two different "files" here:
System.in, the standard input (or "terminal"), which you're using to ask the user for a filename
the file with the name you get from the user
When you call name = kb.nextLine();, you're asking the parameter (the Scanner built with System.in) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.
As quazzieclodo noted above, you probably only need to call readLine once.
After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.
Assuming that your intention is to use Scanner to read a text file:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}