I am working on a simple program that takes input from user and then saves it with specific file name.
To be more precise:
public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;
public static void main(String[] args) throws IOException {
System.out.print("File name: ");
name = in.nextLine();
fw = new FileWriter(name + ".txt", false);
System.out.println("Continue typing/type save to quit");
while(!quit) {
String word = in.nextLine();
if(word.equals("save")) {
fw.close();
quit = true;
}
else {
fw.write(word + "\n");
}
}
Program asks for file name.
User is typing words until he types "save" which saves the file
As you can see program ask user for file name at the beginning, before he starts to type. This is my problem. I want my program to ask the user for a file name at the end, after he typed all words. Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.
I would like to know is there any solution to my problem or what kind of information should I look for.
You have two options:
Store all the user input in memory (in a List<String> for instance) and then write out the words after seeing the save keyword and getting the output filename from the user.
Open the output file as you are doing, but with a temporary name, and write the words as you read them. Upon seeing the save keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.
Unless you need to process millions of words I'd go with option 1 for its simplicity.
Related
My objective is to eventually make a spell checker but I need a dictionary of words to do that.
Here I'm trying to allow the user to input any number of text files as long as there's a space in between the file names ("novel1.txt novel2.txt novel3.txt").
I will use every word from these novels to write to a .dat file of individual words on individual lines(i.e. a dictionary of words). However I'm getting a file not found error at Scanner read = new Scanner(new File(filenames[i])); even though I know that I have the file.
I have even tried putting it in the source package to make sure it could be found.
At the very bottom of my code is a small test I ran (commenting out the other code first) and it does indeed print "war.txt isn't a file," even though I can clearly see that I have the txt file and have typed it correctly.
Can somebody tell me why java isn't seeing my txt file or maybe doesn't think it is a normal file?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}
I believe you do something in a wrong way. Try following example and compare it with your actual file locations.
Demo.java
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
compile and run it
javac Demo.java
java Demo
output
war.txt isn't a file.
now create in the same directory the war.txt
echo "foobar" > war.txt
run the code again
java Demo
output
war.txt is a file.
For the FileNotFoundException make sure that files are in your classpath if you insert only the filenames (for example if you use eclipse put the files on the root folder of the project).
For the war.txt issue you should do this:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
This because when you do File war = new File("war.txt"); you are not creating the file, you have to explicitily create it with war.createNewFile();.
Finally, pay attention here:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
You do two times read.next() without check read.hasNext() the second time. You should write something like that:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}
I'm trying to make it so whenever a user inputs a name and pass it will write that information(in the format of name,pass) to a .csv file specified by the location. However whenever I run the program, it keeps overwriting the first line. I tried adding "\n" and out.newLine(); but for some reason it doesn't write to the next line. I have no idea why it does this so I was hoping if someone knows why.
public class TestClass {
public static void main(String[] args) throws IOException {
String location = "my location to the file (.csv)";
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.next();
System.out.print("Pass: ");
String pass = sc.next();
BufferedWriter out = new BufferedWriter(new FileWriter(location));
out.write(name + "," + pass + "\n");
out.newLine();
out.close();
}
}
Currently in the file I have this:
test, one
and when I ran the program:
name: one
pass: two
exited the program and checked the file and the first line was replaced with one,two instead of making it like this:
test, one
one, two
Thank you for those who help :)
Use the second constructor of FileWriter:
FileWriter(String fileName, boolean append)
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
BufferedWriter out = new BufferedWriter(new FileWriter(location, true));
I have a basic User Input and System Output program using strings, and at the start of the program it asks for the user's name, which it saves as a string variable inside the program.
Scanner input = new Scanner(System.in);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
What I want is for the program to save all new names it receives in an external file (like a
text file), and whenever a name is input it checks to see if it has encountered that name before. I want to use an if / else statement to have it display a different output depending on whether or not it has seen that name before. How do I go about accomplishing this?
~
My apologies if this is a basic problem (or if it has been answered before), but I am relatively new to java and I wasn't able to find a solution. Thank you for your help! ^-^
I think this program may accomplished your requirement
public static void main(String as[]) throws Exception{
int i=0;
File f1=new File("D:\\Name.txt");
FileWriter fw=new FileWriter(f1,true);
Scanner input = new Scanner(System.in);
Scanner output=new Scanner(f1);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
if(!f1.exists()){
f1.createNewFile();
}
else{
while(output.hasNext()){
String na=output.next();
if(na.equals(name)){
++i;
break;
}
}
if(i==0)
fw.write(name+" ");
else{
System.out.println("Please enter some different name");
}
}
fw.close();
input.close();
output.close();
}
I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.
I'm currently writing this program that I require to read info from a text file and to then compare the info read to a user input and output a message saying if it was a match or not.
Currently have this. The program is sucessfully reading the data specified but I can't seem to compare the strings correctly at the end and print a result.
Code is below any help would be greatly appreciated.
import java.util.Scanner; // Required for the scanner
import java.io.File; // Needed for File and IOException
import java.io.FileNotFoundException; //Required for exception throw
// add more imports as needed
/**
* A starter to the country data problem.
*
* #author phi
* #version starter
*/
public class Capitals
{
public static void main(String[] args) throws FileNotFoundException // Throws Clause Added
{
// ask the user for the search string
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter part of the country name: ");
String searchString = keyboard.next().toLowerCase();
// open the data file
File file = new File("CountryData.csv");
// create a scanner from the file
Scanner inputFile = new Scanner (file);
// set up the scanner to use "," as the delimiter
inputFile.useDelimiter("[\\r,]");
// While there is another line to read.
while(inputFile.hasNext())
{
// read the 3 parts of the line
String country = inputFile.next(); //Read country
String capital = inputFile.next(); //Read capital
String population = inputFile.next(); //Read Population
//Check if user input is a match and if true print out info.
if(searchString.equals(country))
{
System.out.println("Yay!");
}
else
{
System.out.println("Fail!");
}
}
// be polite and close the file
inputFile.close();
}
}
You should try reading the input from a textField in an user interface(visible window) where the user puts the country and getting that as raw input shortens the code.(Only if you have a visible window on screen)
I don't have that good experience with scanners, because they tend to crash my applications when I use them. But my code for the same test does only include a scanner for the file which does not crash my application and looks like following:
Scanner inputFile = new Scanner(new File(file));
inputFile.useDelimiter("[\\r,]");
while (inputFile.hasNext()) {
String unknown = inputFile.next();
if (search.equals(unknown)) {
System.out.println("Yay!");
}
}
inputFile.close();
I think the easiest way to compare string against a file is to add a visible window where the user types the country, and reading the input to a string with String str = textField.getText();
I am guessing that your comparison is failing due to case-sensitivity.
Should your string comparison not be CASE-INSENSITIVE?
There are a few possible issues here. First, you're converting the searchString to lower case. Are the data in the CSV also lower case? If not, try using equalsIgnoreCase instead. Also, it seems to me like you should be able to match parts of the country name. In that case, equals (or equalsIgnoreCase) would only work if the user inputs the complete country name. If you want to be able to match only a part, use contains instead.