I am pretty new to Java, kind of getting the hang of it, and am working on some code for a Caesar Cipher in my CS class. I have it able to read one line of code from a file and it can decrypt and encrypt just fine, but I think my teacher wants a full document to be able to be encrypted or decrypted. I know it's possible to have it read the entire document and store it into a string, but how would I go about doing that?
Thanks for any help! Let me know if you need to see my other Class, if you need it for reference.
import java.util.Scanner;
import java.io.*;
public class Project3 {
public static void main(String[] args) {
Cipher caesar = new Cipher();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a filename to encode or decode.");
String f = input.nextLine();
String fileName = f;
String line = null;
System.out.println("Enter the number of steps to encode or decode the file by: ");
int i = input.nextInt();
input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
System.out.println("What would you like to do? Enter [e] to encrypt or press [d] to decrypt.");
String a = input.nextLine();
if(a.equals("e")){
String encoded = caesar.useCipher(line,i);
caesar.writeToFile(encoded);
break;
}
if(a.equals("d")){
String decoded = caesar.useCipher(line,(-i));
caesar.writeToFile(decoded);
break;
}
}
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
Your code already has the loop to process the entire file.
The only problem is the prompt asking what the user wants to do. THAT part belongs outside (before) the while loop.
Related
This is my current code:
import java.util.*;
import java.io.*;
public class Adding_Deleting_Car extends Admin_Menu {
public void delCar() throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
I would like to delete a certain line of text from a file based on user input. For instance, this is my text file:
AB234KXAZ;Honda;Accord;1999;10000;3000;G
AB234KL34;Honda;Civic;2009;15000;4000;R
CD555SA72;Toyota;Camry;2010;11000;7000;S
FF2HHKL94;BMW;535i;2011;12000;9000;W
XX55JKA31;Ford;F150;2015;50000;5000;B
I would like the user to input the String of their choice, this will will be the first field in the column (eg. XX55JKA31), and then have that line of text deleted from the file. I've found some code online, but I've been unable to use it successfully.
My current code seems to just rewrite everything in the temporary text file, but doesn't delete it.
You are using File.renameTo, which is documented here:
https://docs.oracle.com/javase/8/docs/api/java/io/File.html#renameTo-java.io.File-
According to the documentation, it may fail if the file already exists, and you should use Files.move instead.
Here is the equivalent code with Files.move:
boolean successful;
try {
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
successful = true;
} catch(IOException e) {
successful = false;
}
Note:
Your code which searches for the VIN is also wrong. See Jure Kolenko's answer for one possible solution to that issue.
Moving forward, you should consider using an actual database to store and manipulate this type of information.
Your error lies in the
if(trimmedLine.equals(lineToRemove)) continue;
It compares the whole line to the VIN you want to remove instead of just the first part. Change that into
if(trimmedLine.startsWith(lineToRemove)) continue;
and it works. If you want to compare to a different column use String::contains instead. Also like Patrick Parker said, using Files.move instead of File::renameTo fixes the renaming problem.
Full fixed code:
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Adding_Deleting_Car{
public static void main(String... args) throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
Note that I changed the class definition not to inherit and the method definition to main(String... args), so I could compile on my system.
I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
Here is my txt file look like.
admin 12345
funny 123
loop 12390
Hi guys. I am trying to replace particular text in my txt file. For example, I want to replace admin's 12345 with something else that I key in in my input2, it means I want to replace the String(pass) that I find out from txt file through scanner. If I use bufferedwritter, the whole content is going to rewrite..How o solve this problem. I am newbie of programming, kindly need you all help.
login.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
if(e.getSource()==login)
{
Scanner read = new Scanner(new File("oop.txt"));
boolean loginTry = true;
while(read.hasNext())
{
String user = read.next();
String pass = read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
loginTry=false;
break;
}
}
if(!loginTry)
{
JOptionPane.showMessageDialog(this,"Login Successful");
}
Here is a simple example on how to do what you want!
//Replace a line or word in a file
import java.io.*;
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
OUTPUT
file.txt
I drink Java
I sleep Java
This is test string 1
This is test string 20000
I did both because the way your txt file is you have more than just a word, you have an ID number of some sorts right next to your users login information. So i would use change line!
Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)