Taking a beginners course in Java and I am stuck on one of the exercises. We're meant to print the text within a specific file, which we can find via the file's name which was inputted by a user. In our previous exercise, we learned that
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
would find the text within the file "data.txt", but I am unsure about how to convert this into finding any file name inputted by the user.
More details below.
Exercise: Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided. You may assume that the user provides a file name that the program can find.
The exercise template contains the files "data.txt" and "song.txt", which you may use when testing the functionality of your program. The output of the program can be seen below for when a user has entered the string "song.txt". The content that is printed comes from the file "song.txt". Naturally, the program should also work with other filenames, assuming the file can be found.
My code so far is:
import java.nio.file.Paths;
import java.util.Scanner;
public class PrintingASpecifiedFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which file should have its contents printed?");
String fileName = scanner.nextLine();
//try(Scanner scanner = new Scanner(Paths.get(fileName))) {
try(scanner = Paths.get(fileName)) { // this part of the code is underlined red
while (scanner.hasNextLine()){
String output = scanner.nextLine();
System.out.println(output);
}
}
catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
I have tried searching how to add a new scanner as that was a suggestion but every time I've tried it gets an error. Also the "try" section is underlined red and cannot seem to figure out why. The underlined red part says variables in try-with-resources are not supported in -source 8
If anyone has tips, I would really appreciate it! Thank you!
You used one Scanner for reading the file path from the console.
You need an other Scanner (or reader alternative) for reading the file.
try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {
Related
I am very new to coding and learning java, I can picture what the program needs to do however implementing to code has proven tough for me. I am trying to create a constructor. The constructor needs to do the following-
Constructor: When reading in and storing the individual quiz data, you will need to watch out for repeated quizzes. If a quiz is read in with a date that already has an entry stored, you will need to replace the earlier entry with the new one. I have been provided a java doc for this, however I will need to create the code. I have attached an image of the javadoc as well as the code that I currently have.
Javadoc for Constructor
public QuizList(String filename)
{
this.quizzesList = 0;
this.quizList = new ArrayList<Quiz>();
try {
Scanner infile = new Scanner(new File(filename));
while (infile.hasNextLine()){
String quizDate = infile.next();
String pointsEarned = infile.next();
String possiblePoints = infile.nextLine().trim();
Quiz quiz = new Quiz(quizDate, points, possible);
this.quizzes.add(quiz);
}
infile.close();
}
catch (java.io.FileNotFoundException e) {
System.out.println("No such file: " + filename);
}
File has lastModified method: https://docs.oracle.com/javase/8/docs/api/java/io/File.html.
I recommend you to iterate the files on the directory and check their last modified date.
So the goal of my code is to read the text file in using Scanner and then take the user input via text fields.
The scanner will then iterate through the text file trying to find an instance of said user input, if that input is then found, it replaces the word within the text file.
I then write back to the file, with just that one word changed.
My problem is that I have not used Scanner before and going through the docs, I am unsure of how to proceed correctly.
Here is my code so far that activates at the click of a button:
Scanner read = new Scanner("test test.txt");
//Converting user input from editSerialField to a scanner
Scanner scEditSerial = new Scanner(editSerialField.getText());
String scSerial = scEditSerial.nextLine();
//Converting user input from editLocationField to a scanner
Scanner scEditLocation = new Scanner(editLocationField.getText());
String scLocation = scEditSerial.nextLine();
while (read.hasNextLine())
{
//If my text file contains the user input from the text field
if (read.hasNext(scSerial))
{
//Code to replace instance of editSerialField in text file
}
//Code to write back to the file
}
How do I use Scanner to replace words within a text file? Am I to use a different class to do so?
I'm stuck as to how to proceed with my code, so any help would be greatly appreciated.
You cannot do it using Scanner class. as Scanner class is used to read only. you can replace the words as below:
Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));
Or you can also see BufferedWriter or FileWriter. You can go through the working example here
Hey here is my code i have created its a simple file creation program as i have only been using java for the past 2 days. I'm only 13 so please be simple :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Filecreator
{
public static void main( String[] args )
{
Scanner read = new Scanner (System.in);
String y;
String u;
try {
System.out.println("Please enter the name of your file!");
y = read.next();
while (y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")){
System.out.println("Your Filename contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file name");
y = read.next();
}
System.out.println("Please enter the file type name");
u = read.next();
while (u.contains(".") || u.contains(",") || u.contains("{") || u.contains("}") || u.contains("#") ){
System.out.println("Your File-type name contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file-type name");
u = read.next();
}
File file = new File( y + "." + u );
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("The name of the file you have created is called " + y + file);
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you run it on a program such as Eclipse you will see the output. But i want to be able to edit the [file's] contents before i finally choose the name and the file type and then save it. Is there anyway i can do this? Thanks - George
Currently you are printing everything out to the console - this is done when you use System.out.println(...).
What you can do is to write the output somewhere else. How you can do this ? The easiest way how to do this is to Use StringBuilder:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
This is a code sample :
StringBuilder sb = new StringBuilder();
sb.append("one ");
sb.append("two");
String output = sb.toString(); // output contains string "one two"
Now you have your whole output in one string. If you look at StringBuilder documentation (link is above) you can see that there are other useful methods like insert or delete that help you to modify your output before you convert it to string (with toString method). Once all your modifications are done you can write this string to a file.
For writing a String to a file this could be helpful :
How do I save a String to a text file using Java?
This is good enough approach if you are writing small files (up to few MB). If you want to write bigger files you shouldn't store the whole string in memory before you write it to a file. In such scenarios you should create smaller strings and write them to a file. There is a good tutorial for that :
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Read lines until the line contains a special end-of-file marker. Eg, the old unix program 'mail' append all lines until a line consisting of a single '.' is read.
// insert this before reading the filename
StringBuilder content = new StringBuilder();
s = read.next();
while( !s.equals(".")) {
content.append(s);
content.append(String.format("%n"));
s = read.next();
}
The look at this: write a string into file (better answer than the other) and use that as an example of how to actually write the contents to the file, after it has been created.
p.s.
Pro-tip: I'm sure you have noticed that you have duplicated exactly the same line for checking if a filename is valid. A good programmer would notice this too and "extract" a method that does the logic in one place.
Example:
boolean isValidFilename( String s ) {
return !(y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")));
}
You may then replace the checks;
while (!isValidFilename( u )){
System.out.println("Your File-type name contains an incorrect character...etc");
}
This is good since you don't have to repeat tricky code, which means there are fewer places to do errors in. Btw, the negations (!) are there to avoid negative names (invalid=true) because you might end up with a double negation when using them (not invalid=true) and that may be a bit confusing.
You can't edit a file before you create it. You can make changes to the data you are going to write to the file once you crate it; since you control both that data and the creation of the file, there should be no problem.
I'm currently working on a java program that requires you to use several scanners on several txt files to return definitions of names, as well as a few numbers that go along with them about their popularity. Currently, I'm having difficulty returning this data back to the original program.
An example of how the .txt File with the definitions is as follows:
ADAMO m Italian Italian form of ADAM
ADAN mf (no meaning found)
ADANNA f Igbo Means "father's daughter" in Igbo.
ADANNAYA f Igbo Means "her father's daughter" in Igbo.
ADAOIN f Irish Modern form of TAN
My program currently looks like this thus far:
import java.io.*;
import java.util.Scanner;//For reading the file.
public class BabyNamesProject {
//This program will use user input to scan several text documents for information regarding names.
//It will give the popularity of the name in the last few decades, it's meaning, and a Drawing Panel chart with it's popularity.
public static void main(String[] args)
throws FileNotFoundException {
File f = new File("Names.txt");
File g = new File("Meanings.txt");
File h = new File("Names2.txt");
Scanner nameCheck = new Scanner(f);
Scanner meaningCheck = new Scanner(g);
Scanner popularityCheck = new Scanner(h);
Scanner Ask = new Scanner(System.in);
String userName = "";
String upperUserName = "";
String meaning = "";
System.out.println("Hello! This application will allow you to check how popular certain names are compared to others.");
System.out.println(" ");
System.out.println("Please type in your name!");
userName = Ask.next();
upperUserName = userName.toUpperCase();
if (meaningCheck.hasNext(""+ upperUserName))
meaning = meaningCheck.next("" + upperUserName);
System.out.println("" + meaning);
System.out.println("" + userName +"! That's one the rarest cards in all of duel monsters!");
}
}
As you may notice, it's nowhere near finished, but what I can't seem to figure out is how to both search the .txt file, using the uppercase name the user imputs, and how to make it return the entire line. So far, it seems like plenty of searches on here have led me to carriage returns, which I at least understand how they work, but not how to use one. If anyone has time to explain something I could do to solve this, it would be greatly appreciated!
The method is called nextLine():
File f = new File("text.txt");
Scanner s = new Scanner(f);
String line = s.nextLine();
You can use a BufferedReader to read the text file line-by-line and do whatever you please with it.
Have a look here: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
I am trying to read a text file in order to copy some parts of it into a new text file.
This is how I create my Scanner item :
// folder
File vMainFolder = new File(System.getProperty("user.home"),"LightDic");
if (!vMainFolder.exists() & !vMainFolder.mkdirs()) {
System.out.println("Missing LightDic folder.");
return;
}
// file
System.out.println("Enter the source file's name : ");
Scanner vSc = new Scanner(System.in);
String vNomSource = vSc.next();
Scanner vSource;
try {
vSource = new Scanner(new File(vMainFolder, vNomSource+".txt"));
} catch (final java.io.FileNotFoundException pExp) {
System.out.println("Dictionnary not found.");
return;
}
And this is how I wrote my while structure :
while (vSource.hasNextLine()) {
System.out.println("test : entering the loop");
String vMot = vSource.nextLine(); /* edit : I added this statement, which I've forgotten in my previous post */
}
When executing the program, it never prints "test : entering the loop".
Of course, this file I am testing is not empty, it is a list of words like so :
a
à
abaissa
abaissable
abaissables
abaissai
I don't understand what I did wrong, I've used this method a few times in the past.
Problem solved.
I don't really know why, but I solved the problem changing the encoding of my FRdic.txt file from ANSI to UTF-8, and then the file was read.
Thanks to everyone who tried to help me.
Is it normal that a text file encoded in ANSI is not read by the JVM ?