I am trying to process text from a user entered file when compiled the scanner in cannot be found. I am assuming it is being caught. what can I do to make this work?
String namef = getf.nextLine();
File inPut = new File(namef);
try {
Scanner in = new Scanner(inPut);
}
catch (FileNotFoundException e) {
System.out.println("file not found");
}
while(in.hasNextLine()) { // process file
String line = in.nextLine();
String pLine = parse(count, namef);
}
#Tom is right. You must declare the scanner outside the try block.
String namef = getf.nextLine();
Scanner in = new Scanner();
File inPut = new File(namef);
try
{
in = new Scanner(inPut);
while(in.hasNextLine()) // process file
{
String line = in.nextLine();
String pLine = parse(count, namef);
}
}
catch (FileNotFoundException e)
{
System.out.println("file not found");
}
Related
Code:
public static void createMovie() {
String fileName = "C:\\Users\\kat7r\\eclipse-workspace\\Final OOPs project\\src\\movielist.txt";
File movieFile = new File(fileName);
try {
Scanner inputStream = new Scanner(movieFile);
inputStream.next();
while (inputStream.hasNext()) {
String movieArgs = inputStream.next();
String[] splitData = movieArgs.split(",");
System.out.println(movieArgs);
//int priority = Integer.parseInt(splitData[0]);
//System.out.println("Priority: "+priority);
}
} catch(FileNotFoundException e) {
System.out.println("File not found.");
Expected output:
Priority,Name,Genre,Length,Rating
1,Inception,Science Fiction,2.47,8
2,Shawshank Redemption,Drama,2.37,9
3,Coco,Fantasy,1.82,8
4,Lord of the rings,Fantasy,3.8,9
5,Thor: Ragnarok,Fantasy,2.17,8
Actual output;
1,Inception,Science
Fiction,2.47,8
2,Shawshank
Redemption,Drama,2.37,9
3,Coco,Fantasy,1.82,8
4,Lord
of
the
rings,Fantasy,3.8,9
5,Thor:
Ragnarok,Fantasy,2.17,8
Comments:
Essentially the spaces are causing the IDE to start a new line. I tried using .nextLine but that didn't help. Tried going online as well.
Did you use :
inputStream.nextLine();
while(inputStream.hasNextLine())
{
String movieArgs = inputStream.nextLine();
String[] splitData = movieArgs.split(",");
System.out.println(movieArgs);
}
Since you want to read the whole line of the input, use inputStream.nextLine() instead of inputStream.next(). Refer to this topic.
It works for me:
public static void createMovie() {
String fileName = "C:\\Movies.txt";
File movieFile = new File(fileName);
try {
Scanner inputStream = new Scanner(movieFile);
while (inputStream.hasNextLine()) {
String movieArgs = inputStream.nextLine();
System.out.println(movieArgs);
}
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
I'm trying to write a do while loop that will read a file that the user input and read it out and will loop until the user types end. The do part is working, but my while just isn't being activated and I'm struggling to figure out why.
public static void readingFiles() throws Exception {
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
input = new Scanner(System.in);
if(input.hasNextLine())
{
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found. Please try again.");
fileFound = false;
continue;
}
catch (IOException e)
{
System.out.println("There was an IOException. Please try again.");
continue;
}
catch (Exception e)
{
System.out.println("There was an exception. Please try again.");
continue;
}
finally
{
{
if(fileFound)
reader.close();
}
}
}
} while(!input.nextLine().equalsIgnoreCase("end"));
}
I've tried using an if statement before my input.hasNextLine() but then it would ignore the rest of the whole program and do nothing and only typing end would work. I've tried using && in my current if statement too but that didn't work. And I tried using a boolean that I set to true if string contained end. I think the problem may be in the input.hasNextLine but I'm not sure why or what to change it to?
Thanks for any help
Calling input.nextLine() again will not preserve your previous input string.
Store it in a variable, and compare that
public static void readingFiles() throws Exception {
BufferedReader reader = null;
String filename = null;
Scanner input = new Scanner(System.in);
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
if(input.hasNextLine()) {
filename = input.nextLine();
try {
File f = new File(filename);
// reader =
...
} while (!filename.equalsIgnoreCase("end");
Here are two versions of the same method. the first one uses JOptionPane and the second one uses console. They are supposed to take a file path (string) from user input to find the file and read it.
The first method works just fine but the second method which uses console gave me a FileNotFoundException error. Why doesn't the second one work if they both are almost identical?
//USING JOptionPane
////////////////////////////////////////////////////////////////
public void addFromFile() {
String[] option1 = { "Go back to Main Manu", "Continue" };
int choice4 = JOptionPane.showOptionDialog(null,
"Warning: this method will delete existing data before it add file data", "Monster Database",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option1, null);
if (choice4 == 0)
monitor();
if (choice4 == 1) {
monsterAttackList.clear();
Scanner input = new Scanner(System.in);
String filePath = JOptionPane.showInputDialog(null, "Enter a filepath");
File inFile = new File(filePath);
try {
Scanner fileReader = new Scanner(inFile);
String line;
String[] part;
int attackID;
String monster;
String date;
String location;
String reporter;
while (fileReader.hasNextLine()) {
line = fileReader.nextLine();
part = line.split(",");
attackID = Integer.parseInt(part[0]);
monster = part[1];
date = part[2];
location = part[3];
reporter = part[4];
monsterAttackList.add(new MonsterAttack(attackID, monster, date, location, reporter));
}
fileReader.close(); // Close to unlock.
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "filepath is not valid");
System.err.println(e);
}
}
}
// USING SCANNER
///////////////////////////////////////////////////////////////////////////
public void addFromFile() {
System.out.println("Warning: this method will delete existing data before it add file data");
System.out.println("\n1. Go back to Main Manu" + "\n2. Continue \n");
Scanner input = new Scanner(System.in);
int choice4 = input.nextInt();
if (choice4 == 1)
monitor();
if (choice4 == 2) {
monsterAttackList.clear();
System.out.println("Enter a filepath");
String filePath = input.nextLine();
File inFile = new File(filePath);
try {
Scanner fileReader = new Scanner(inFile);
String line;
String[] part;
int attackID;
String monster;
String date;
String location;
String reporter;
while (fileReader.hasNextLine()) {
line = fileReader.nextLine();
part = line.split(",");
attackID = Integer.parseInt(part[0]);
monster = part[1];
date = part[2];
location = part[3];
reporter = part[4];
monsterAttackList.add(new MonsterAttack(attackID, monster, date, location, reporter));
}
fileReader.close(); // Close to unlock.
input.close();
} catch (IOException e) {
System.out.println("filepath is not valid");
System.err.println(e);
}
}
}
You will want to put a call to input.nextLine() after every call to input.nextInt(). NextInt does not consume the newline character, only the number.
I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.