Why is FileNotFoundException popping up? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to print Ben, Adam, John and Smith into a txt file with the names on separate lines. I am partly successful, however I keep getting FileNotFoundException at the end after the code runs. Why is that?
"Ben Adam John Smith" passes through String names
File Writing code:
public String writeYourName(String names) throws Exception {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("names.txt")));
for(int i = 0; i < 1; i++) {
output.write(names);
}
output.close();
Scanner scan1 = new Scanner(new File("names.txt"));
while(scan1.hasNext()) {
if(scan1.hasNext()) {
System.out.println(scan1.next());
}
}
return names;
}
Test file for FileWriting:
FileWriting fileWriting = new FileWriting();
FileReading fileReading = new FileReading();
fileWriting.writeYourName("Ben Adam John Smith");
System.out.println(fileReading.readName1(fileWriting.writeYourName("Fred")));
Code that the error points to:
public class FileReading {
public String readName1(String nameFile) throws Exception {
-> Scanner scan = new Scanner(new File(nameFile)); <-
String name = scan.next();
String nextLine = "";
while(scan.hasNextLine()) {
nextLine = scan.nextLine();
}
return name + " " + nextLine;
}
Test file for FileReading:
System.out.println(fileInput.readName1("namefile.txt"));

You are trying to read a file where the filename consists of a name or names here:
fileReading.readName1(fileWriting.writeYourName("Fred"))
as writeYourName doesn't return a file name but a string of names of persons (or in this case, one name, of one person: Fred):
return names;

Related

how to read the number of columns in text file in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
how to read the number of columns in text file in java.
Example text file as below. Comma separated. In this i need to get the total column as count 4
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
The simplest way is to use a Scanner and read the 1st line.
By using split() with , as a delimeter you get an array and its length is what you want.
public static int getFileColumnsNumber(String filename) {
File file = new File(filename);
Scanner scanner;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(",").length;
}
scanner.close();
return number;
}
public static void main(String[] args) {
String filename = "test.txt";
System.out.println(getFileColumnsNumber(filename));
}

Read lines from a file and compare their equality [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to write a progam to read a text file and compare its lines. I want to store them in an array, but I do not how to do this and how to compare, if they are equal.
package pantoum;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Pantoum {
public static void main(String[] args) throws FileNotFoundException {
//get filename input from user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the full file name: ");
String fileName = keyboard.nextLine();
File inputFile = new File(fileName);
if (inputFile.exists()){
//create scanner to read file
Scanner input = new Scanner(inputFile);
//while (input.hasNext());{
String title = input.next();
System.out.println(title);
}
else
{
System.out.println("Sorry, that file does not exist.");
}
}
}
i personally prefer to use buffered reader when it comes to reading from a text file.
boolean equal=false;
String lines[] =new [10];
// or however long the array needs to be.
int count=0;
BufferedReader infile = new BufferedReader(new FileReader("<Name of file>"));
do {
lines[count] = infile.readLine();
count++;
} while (lines[count] != null);
for(int i=0;i<lines.length();i++) {
for(int j = i+1; j<lines.length()-1;j++){
if(lines[i].equals(lines[j])){
equal=true;
system.out.print(lines[i]+" and "+lines[j]+" are equal");
}}}
if(!equal){
system.out.print("Sorry your text did not equal any text from the text file");
}
i hope this helped and i hope i have explained everything well enough for you to understand, if not feel free to ask.
I personally would read each line into a String[] position and then in a loop check if String[i].equals(String[j]). If you need a rough idea how to code this let me know.
You can just use scanner's nextLine() method to get an entire line and then compare them using String.equals()
something like
String line1 = input.nextLine();
String line2 = input.nextLine();
if(line1.equals(line2){
doStuff();
}

How to edit a record in java text file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a text file which have contents like this:
1 John 200
4 Jack 144
7 Sarah 123
the programming format of this record is
int id, String name, int quantity
My question is how to edit record like this:
Enter id of the record you want to edit?
1
New Name:
Terry
New Quantity:
700
so after doing this the file must be like this:
1 Terry 700
4 Jack 144
7 Sarah 123
but I am stuck in this code because I am still a java beginner?
Here is your code. Let me know if you need explanation :D
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ScanFile {
public static void main(String[] args)throws IOException {
String newName=null;
String newQuantity=null;
boolean checked = true;
File f= new File("E:\\myFile.txt"); // path to your file
File tempFile = new File("E:\\myTempFile.txt"); // create a temp file in same path
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner sc = new Scanner(f);
System.out.println("Enter id of the record you want to edit?");
Scanner sc2 = new Scanner(System.in);
int id = sc2.nextInt();
while(sc.hasNextLine())
{
String currentLine= sc.nextLine();
String[] tokens = currentLine.split(" ");
if(Integer.valueOf(tokens[0])==id && checked)
{
sc2.nextLine();
System.out.println("New Name:");
newName= sc2.nextLine();
System.out.println("New Quantity:");
newQuantity= sc2.nextLine();
currentLine = tokens[0]+" "+newName+" "+newQuantity;
checked = false;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
sc.close();
f.delete();
boolean successful = tempFile.renameTo(f);
}
}

How to pass info to the constructor from a text file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Suppose there're two classes: Exam and MainExam (contains a main method). class Exam has a constructor
public Exam(String firstName, String lastName, int ID)
The class MainExam reads data from a tex tfile. For example, the data can be:
John Douglas 57
How can one pass data to the constructor from a textfile?
Here is the code that reads the file (just in case you don't actually have it)
Scanner scanner = new Scanner(new File("C:\\somefolder\\filename.txt");
String data = scanner.nextLine();
Now, assuming your file lines are in the following format:
<FirstName> <LastName> <id>
without any whitespace in each element, you can use the regex " " to String#split your data
String[] arguments = data.split(" ");
and then pass them into the constructor (String, String, int)
String fn = data[0];
String ln = data[1];
int id = Integer.parse(data[2]);
new Exam(fn, ln, id);
You can refer the following snippet to store the contents of your text file in a string object:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
The contents of the file are in sCurrentLine object now. Using StringTokenizer you may separate the firstname, lastname and ID using space as delimiter. Hope this helps!!
You can use StringTokenizer to break the data into parts that were read by MainExam.
String str; //data read by MainExam, like: John Douglas 57
String[] values = new String[3]; // size acording to your example
StringTokenizer st = new StringTokenizer(str);
int i=0;
while (st.hasMoreTokens()) {
values[i++] = st.nextToekn();
}
Now you have the data separated in the array values.

String split based on column (Java) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
New to java. I want to read in a file that has lines formatted like this
en Fox 3 1344
en Bird 19 144
en Dog 93 1234
For each line I want to pick the contents of column 2 and 3. In the case of the first line "Fox" and "3". and display them. So far this is what I have.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class pagecounts {
public static void main(String[] args) throws FileNotFoundException {
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
*// letter in column 2 and 3 pick code goes here.*
System.out.println(content);
}
}
Any help will be appreciated.
Assuming that each column can contain only one value (word/number) you can use Scanner to read all tokens form one line and use only these which interest you.
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNext()){
String col1 = sc.next();
String col2 = sc.next();
int col3 = sc.nextInt();//you can also use next() if you want to get this token as String
int col4 = sc.nextInt();//same here
System.out.printf("%-15s %d%n", col2, col3);
}
}
You can also read file line by line and split each line on space
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNextLine()){
String line = sc.nextLine();
String[] tokens = line.split("\\s+");//I assume there are no empty collumns
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
}
}
You can also treat this file as CSV file (Comma Separated Values) where values are separated with space. To parse such file you can use library like OpenCSV with separator defined as space
try(CSVReader reader = new CSVReader(new FileReader(path),' ')){
String[] tokens = null; // ^--- use space ' ' as delimiter
while((tokens = reader.readNext())!=null)
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
} catch (IOException e) {
e.printStackTrace();
}
Use split:
System.out.println(content.split(" ")[1] + " " + content.split(" ")[2]);

Categories