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()"));
Related
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());
}
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!
Hello I am fairly new to java and programming. I was wondering how to read a text file (test.txt) and implement it to carry out a procedure, such as creating and deleting nodes in a linked list as well as assigning them a value. For example if the txt file read:
insert 1
insert 3
delete 3
I would want the program to make a node and assign it a value 1, make a node and assign it a value 3 and then delete that node that has the assigned value 3.
This is some rough code I have so far. Thank you.
CODE:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If the command format in the file is always correct, you can wrap the input stream with Scanner and read word with next(), followed by nextInt() to read the number. No need for complex input validation. This will even allow the number to be on different line from the command.
If you expect invalid input, to make it simple, you can use the current scheme of reading line by line and check the command. Trim and tokenize the line by space with .trim().split("\\s+"). Then compare the first item in the array of tokens and check whether it is a valid command or not. Call the corresponding function to handle the command if valid, print error message otherwise.
If you have multiple commands, you can use Command pattern to make your code more manageable.
I am trying to make a login screen that can read the usernames and passwords from a text file. I have already built the registration page which outputs the username and password to a file by executing the following:
try (BufferedWriter out = new BufferedWriter(fstream)) {
try {
out.write(username + " " + password);
out.newLine();
JOptionPane.showMessageDialog(null,"User Account '" + username + "' Created");
} catch (IOException ex) {
Logger.getLogger(ServerMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
the text file will looking something like this:
user1 password1
user2 password2
I have been reading through a lot of documentation to try and figure this one out however the more reading i do the more confused I get. The reason why I am doing it in this way is so that I can continue reading and writing to .dat files for the information that the system will eventually hold.
If anybody can help me in any way shape of form that would be amazing!
Thanks
C
Quick and easy solution. Each line is commented but if you need any help or if there's anything you don't get please let know.
import java.io.*;
class FileRead
{
public static boolean main(String lineToCompare)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
if(strLine.compareTo(lineToCompare) == 0)
return true;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return false;
}
}
I am really not sure whether you want to execute the above code for a specific username and password, or all of them.
If you want to get specific line from the file, and you already have access to the offset of the line you want to read, you can use RandomAccessFile. This class lets you move the file pointer to a certain position, and then you can simply read the next line to get username and password.
However, if you want to read a specific line but have no information where that line could be in the input file, you will need to read each line (eg., using a BufferedReader) to find the one you need. You can also take this approach, if you want to read the files line by line.
I'm currently attempting to write a role-playing game with Eclipse (don't know how far I'll get, but who knows) and I'd like to prompt the user to answer with a sentence/phrase.
I'm learning very basic Java right now, but we know how to prompt the user to enter in either an integer or a double variable/number (er... mind is a little messed up) - similar to:
variable=input.nextInt();, or input.nextDouble();
Can anyone please list how to prompt the user for a phrase, and how to make the program recognize that certain phrase (and get results)? Thank you.
(One final note: I'm not the best programmer, so can you please list the simplest ways to do so?)
Probably your input is a Scanner, so just use nextLine() to get a line of text. That will wait for the user to enter an arbitrary amount of text and press enter, then you'll get all the text they entered.
Soln:
public static void main(String[] args) {
System.out.println("Enter the phrase");
String line;
try {
BufferedReader input =new BufferedReader(new InputStreamReader(System.in));
while ((line = input.readLine()) != null) {
System.out.println(line);
if(!line.isEmpty()) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println("token=" + st.nextToken());
}
}
}
input.close();
} catch (IOException e){
e.printStackTrace();
}
System.out.println("DONE");
}