Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
recently have gone to test a form of key validation code from files in Java. I'm still new to this(IO) and looking online brings endless methods of approaching this but I'm not capable of distinguishing the various pros & cons between these methods. I would like to present my code and ask me how I should tackle in properly, it works but I'm not all too satisfied.
I know most of you are against advice-oriented questions and if it is the case I'll gladly put the topic down, just wanted to ask for some help beforehand. Thank you
/*
* To be able to give you a rundown of the situation:
* Inside my project file I have a .txt file named 'MasterKey'
* Initially inside this file is a key and validation boolean 'false'
* On start-up the program analyzes this file, if it detecs a key it then
* Asks the user to input the key. If it is valid it then creates/overwrites the
* Previous file with a new .txt with same name but only "true" is inside it.
* If the key is incorrect, it will continue requesting for the key
*/
import java.io.*;
import java.util.Scanner;
public class MasterKeyValidationTest {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
getFileInfo(); //Method below
}
private static void getFileInfo(){
File readFile = new File("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //My file directory
try{
BufferedReader getInfo = new BufferedReader(
new FileReader(readFile));
String fileInfo = getInfo.readLine(); //Gets the key or 'true'
if(fileInfo.contains("true")){ //If file contains 'true', program is valid
System.out.println("Valid");
}else{
System.out.println("Enter Key");
String key = input.next(); //Receive input for the key
if(!fileInfo.contains(key)) { //If the file doesn't contain the key you just entered
System.out.println("Invalid key");
key = input.next(); //Receive another key input
getFileInfo(); //Start the method from top again to check
}
if (fileInfo.contains(key)) { //If the file contains the key you just entered
System.out.println("Program valid");
FileWriter fstream = new FileWriter("/Users/Juxhin's Lab/Desktop/Projects/MasterKey.txt"); //Create/Overwrite the MasterKey.txt file
BufferedWriter out = new BufferedWriter(fstream);
out.write("true"); //Input "true" inside the new file
out.close(); //Close the stream
}
}
}catch(FileNotFoundException e){
System.out.println("File not found");
System.exit(0);
}catch(IOException e){
System.out.println("An IO Error");
System.exit(0);
}
}
}
Some advice ..
1. String fileInfo = getInfo.readLine(); //Gets the key or 'true' .. reads only 1 line (if that is what you want..)
2. use fileInfo =fileInfo.trim() // to remove leading and trailing whitespaces.
3. If you just want to "read" the file, use FileReader, BufferedReader. If you want to "parse" the file, use a Scanner.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");
I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}
with this problem I have, I'd like to hit two birds with one stone.
I'm currently trying to output user input from text fields into an existing .CSV file with data already residing within. My first problem stems from not being able to append to a new line, my code is currently appending to the last item in the .CSV file, thus creating an even longer line, not a new line.
Next, I would like to check my .CSV for possible duplicates of the users input. If a user wants to add a Banana to the list, and code checks through the .CSV file and finds a banana within the file, then we can successfully throw an error and warn the user.
Here's my code currently to attempt to try and append to a new line, but somehow it's just not working:
String fileName = "temp.csv";
try {
FileWriter fileWriter =
new FileWriter(fileName, true);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
bufferedWriter.write("\n" + fruitNameField.getText());
bufferedWriter.write(',');
bufferedWriter.write(quantityOfFruitField.getText());
bufferedWriter.write(',');
bufferedWriter.write(fruitLocationField.getText());
//bufferedWriter.write(',');
bufferedWriter.close();
}
catch(IOException ex)
{
System.out.println("Error writing to file" + fileName + "'");
}
While I am wanting 3 different user inputs and to append to a new line, the code above ends up outputting like this: Banana,2,storeOrange,3,store. It seems to be ignoring the new line command.
Now for my second problem, checking against duplicates. For the life of me, I cannot find any resources relating to checking for duplicates within a text file using java.
This question is mainly for appending to a new line, but if I could get any help on this, that would be amazing.
To my knowledge, in order to check for duplicates, I believe I'd have to import my text file and write it to an array, but what if it's a big file?
Once my file is in an array, I'll check if the user input is equal to any text residing within the array, and if it is, throw an error. That is my approach on this subject, please tell me if I can improve on this any way.
Thanks for your help, much appreciated.
I would suggest to make use of a library like opencsv to read and write to csv files.
Example:
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class JavaApplication28 {
public static void main(String[] args) throws IOException {
String input = fruitNameField.getText();
String filename = "temp.csv";
writeToCsvFile(input,filename);
}
private static void writeToCsvFile(String input, String filename) throws IOException {
if(!isDuplicate(input,filename)){
CSVWriter writer = new CSVWriter(new FileWriter(filename,true), ',');
String[] entries = {fruitNameField.getText(),quantityOfFruitField.getText(),fruitLocationField.getText()};
writer.writeNext(entries);
writer.close();
}
else{
System.out.println("fruitName already exists.");
}
}
private static boolean isDuplicate(String input, String filename) throws IOException {
boolean found = false;
CSVReader reader = new CSVReader(new FileReader(filename));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
for(int i = 0; i<nextLine.length; i++){
if(nextLine[i].equalsIgnoreCase(input)){
found = true;
break;
}
}
}
return found;
}
}
If the file is not enormously big, I would suggest to read the whole file and store it in a Map whose keys are the words you're adding(which you want to check for duplicates).
On every new line, you can check whether the map contains the key(which costs only O(1) so it's highly efficient).
For the newlines, note that it depends on the environment, it may be \r\n (for Windows) or \n for Unix/Mac OS. Best is to use System.getProperty("line.separator");
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
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...
Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.
Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have learnt about BufferedReader as well as BufferedWriter, so I decided to create a small text processor for the command line (meaning without interface, just in cmd/terminal). It asks a user for document name (Which will then create a file) and then user can type sentences. Each time user presses "enter" button, text is entered into the file and new line is created and then allowing user to type more. At the end, it will display a message saying file is created.
NOW, I have encountered a problem where user would not be able to stop the process of entering data and creating file, because the program kept creating new lines despite entering nothing or quit keyword(which i stated in the code in order to quit the program.)
Here is my original code:
import java.io.*;
class TextProcessor
{
public static void main(String[] args)
{
try
{
System.out.println("Please enter name of the file");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //User input
String file = in.readLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //Creating file as well as instance for inputting text to the file.
System.out.println("Enter text");
String line = "";
do
{
line = ins.readLine();
System.out.println(line);
writer.write(line);
System.out.println("Second " + line);
writer.newLine();
}
while(line != "quit()");
//while(line != null);
in.close();
writer.close();
System.out.println("Text is created with entered text");
}
catch(IOException e)
{
System.out.println("Error occured");
}
}
}
However, I found a solution to this, which is replacing do-while block with while one:
int counter = 0;
while(counter != 1)
{
line = in.readLine();
writer.write(line);
if(line.equals("quit()"))
{
++counter;
}
else {writer.newLine();}
}
I have a question about this now, why can't I use do-while statement instead of while, even if it seems logical that the program would work? Thank you for reading this!!!!
P.S. I also wonder if I can bring small improvements to this or any other way creating this type of program. Thanks if you give feedback!
Probably the error asked about the most.
Answer can be found here: How do I compare strings in Java?
while(line != "quit()");
must be
while(!line.equals("quit()"));