How can I read a text file and display it using JoptionPane? - java

I am trying to take in user input and storing it in a text file, I was able to take in the input and storing it but now i am trying to display that input in a JOptionPane window. Can someone please help me. I am new on stackflow and this is my first post.
/*Here i am taking in user input and storing it in a file called "dictionary.txt".*/
public static String addNewWord()throws IOException
{
String newWord = "";
newWord = JOptionPane.showInputDialog(null, "Enter the word you want to add to your dictionary.");
FileWriter aDictionary = new FileWriter("dictionary.txt", true);
PrintWriter out = new PrintWriter(aDictionary);
out.println(newWord);
out.close();
aDictionary.close();
return newWord;
}
/* Now i am trying to read "dictionary.txt" and display it using JOptionPane*/
public static String listDictionary()throws IOException
{
FileReader aDictionary = new FileReader("dictionary.txt");
String aLineFromFile = FileReader;
JOptionPane.showMessageDialog(null, aLineFromFile);
aDictionary.close();
return aLineFromFile;
}

You should use a BufferedReader to read the data back from the file:
public static void listDictionary()throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
String aLineFromFile = null;
while ((aLineFromFile = br.readLine()) != null){
JOptionPane.showMessageDialog(null, aLineFromFile);
}
br.close();
return;
}

Related

FileReader read() method is printing imporperly. Do I need to do any additional conversion besides int(ASCII rep) to char?

Trying to print the read() output of the same program on to the console, the characters are either missing or disarranged. Tried this for different files too, getting the same issue.
The byte Stream class and method,FileInputStream.read()for the same type of code, worked perfectly fine, but this character stream is resulting differently.
import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
class CSRead1
{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(in);
out.print("Enter the filename\t>");
String file = input.next();
try(FileReader fr = new FileReader(file))
{ while(fr.read() != -1)
{out.print((char)fr.read());} } //***reading improperly
}
}
Got this upon execution:
D:\JavaEx\FILE-IO>java CSRead1
Enter the filename >CSRead1.java
ipr aaui.cne;
{asCRa1aaln.ytm*
pbi ttcvi anSrn[ rs hosIEcpin
{
cne nu e cne(n;
u.rn(Etrteflnm\>)
tyFlRae r=nwFlRae(ie)
hl(rra( =-)
{u.rn(ca)rra()}}/**edn mrpry
}
?
For a text file containing the only string "Hello"
D:\JavaEx\FILE-IO>java CSRead1
Enter the filename >sample
el?
You read two chars on every iteration: one in while condition and one in loop body. try to fix this issue and all your code will work fine.
I once had an issue with reading files with UTF-8 encoded characters in them.
The solution was:
String st;
File filedir = new File(filename);
BufferedReader in = new BufferedReader(new InputStreamReader(new
FileInputStream(filedir), "UTF8"));
while((st = in.readLine()) != null) {
System.out.println(st); //prints out properly on my side
}
within your code it would look something like this:
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(in);
out.print("Enter the filename\t>");
String file = input.next();
String st;
File filedir = new File(file );
BufferedReader in = new BufferedReader(new InputStreamReader(new
FileInputStream(filedir), "UTF8"));
while((st = in.readLine()) != null) {
System.out.println(st);
}
}

displaying data from .txt file [closed]

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 4 years ago.
Improve this question
need help, i want to display the name of the person who just logged in, here is my login code
public void Masuk(){
try {
String lokasi = "D:/settings.txt";
String username = txtUser.getText();
String password = txtPass.getText();
FileReader fr = new FileReader(lokasi);
BufferedReader br = new BufferedReader(fr);
String line, user, pass;
boolean isLoginSuccess = false;
while ((line = br.readLine()) != null) {
user = line.split(" ")[1].toLowerCase();
pass = line.split(" ")[2].toLowerCase();
if (user.equals(username) && pass.equals(password)) {
isLoginSuccess = true;
this.dispose();
new Main_Menu(this, rootPaneCheckingEnabled).show();
break;
}
}
if (!isLoginSuccess) {
JOptionPane.showMessageDialog(null, "USERNAME/PASSWORD WRONG", "WARNING!!", JOptionPane.WARNING_MESSAGE);
}
fr.close();
}catch(Exception e){
e.printStackTrace();
}
}
the login is in form, i used JDialog to dipslay the name of the person who just logged in(MainMenu), here is my MainMenu code right now
public void Berhasil(){
String data = "D:/Settings.txt";
try {
FileReader fr = new FileReader(data);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine(),nama;
nama = line.split(" ")[0].toLowerCase();
String message = "Selamat datang "+ nama;
String text;
while ((line = br.readLine()) != null)
txtBerhasil.setText(""+message);
}
catch (FileNotFoundException fnfe) {
fnfe.getMessage();
}
catch (IOException ioe) {
ioe.getMessage();
}
}
the .txt file looks like this
Name Username Password
i only want to write the name of the person who just logged in
I'm assuming you want to read some text (the user's information) from a text file. There are several ways to do it. This is one way:
File file = new File("path/to/file.txt");
Scanner sc = new Scanner(file);
String thisLine = null;
while (sc.hasNextLine()){
thisLine = sc.nextLine();
}
Now you can do whatever you want with thisLine. Say you want the first word in the first line:
String[] words = thisLine.split(" ");
System.out.println(words[0]);
This would print the first word in the first line of your txt file. I used space as the separator but it actually depends on what separator you used in yout txt file when you were saving the info. For instance, you may want to use "\t" if tab was used as the separator.

How to remove the duplicate string?

In my code I have two files in my drive those two files have some text and I want to display those string in the console and also remove the repeated string and display the repeated string once rather than displaying it twice.
Code:
public class read {
public static void main(String[] args) {
try{
File file = new File("D:\\file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file1:");
String first = stringBuffer.toString();
System.out.println(first);
File file1 = new File("D:\\file2.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer1 = new StringBuffer();
String line1;
while((line1 = br1.readLine()) != null){
stringBuffer1.append(line1);
stringBuffer1.append("\n");
}
fileReader1.close();
System.out.println("Contents of file2:");
String second = stringBuffer1.toString();
System.out.println(second);
System.out.println("answer:");
System.out.println(first+second);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Output is:
answer:
hi hello
how are you
hi ya
i am fine
But I want to compare both the strings and if the same string repeated then that string should be displayed once.
Output I expect is like this:
answer:
hi hello
how are you
ya
i am fine
Where the "hi" is found in both the strings so that I need to delete the one duplicate string.
How can I do that please help.
Thanks in advance.
You can pass your lines through this method to parse out duplicate words:
// store unique previous words
static Set<String> words = new HashSet<>();
static String removeDuplicateWords(String line) {
StringJoiner sj = new StringJoiner(" ");
// split on whitespace to get distinct words
for (String word : line.split("\\s+")) {
// try to add word to the set
if (words.add(word)) {
// if the word was added (=not seen before), append to the result
sj.add(word);
}
}
return sj.toString();
}

Address book program with more functionality

I've done a small address book program that allows the user to:
add contact
search contact
delete contact
display all contacts
It ends after you enter one option, I want it to keep running until the user says eg 5- exit
another problem I want the data to written and read to data.dat file
I'm completly new, can some tell me how to split up this into separate classes and inherit each other.
my code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class AddressBookOperations
{
public static void main(String[] args) throws IOException
{
String s = null;
String s2 = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Console in = System.console();
System.out.println(" Please select the required operations.\n"
+ " 1- Add contact\t 2- search contact\t 3- delete contact\t 4- display all contacts\n");
s2 = in.readLine();
if (s2 != null && !(s2.equals("1") || s2.equals("2") || s2.equals("3") || s2.equals("4")))
{
System.out.println("Invalid Operation Selected\n");
System.exit(0);
}
else
{
s = s2;
}
if (s != null)
{
String dataLine;
String data;
if (s.equals("1")) {
System.out.println("Name: ");
dataLine = in.readLine();
data = dataLine;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("PhoneNumber: ");
dataLine = in.readLine();
data = data + ":" + dataLine;
writeToFile("C:/AddressBook.bat", data, true, true);
} else if (s.equals("2")) {
System.out.println("Enter Name 0r PhoneNumber: ");
dataLine = in.readLine();
String result = readFromFile("C:/AddressBook.bat", dataLine);
System.out.println("Search Results\n" + result);
} else if (s.equals("3")) {
System.out.println("Enter Name: ");
dataLine = in.readLine();
data = dataLine;
System.out.println("PhoneNumber: ");
dataLine = in.readLine();
data = data + ":" + dataLine;
deleteFromFile("C:/AddressBook.bat", data);
} else if (s.equals("4")) {
String result = readFromFile("C:/AddressBook.bat", null);
System.out.println("Search Results\n" + result);
}
}
}
private static void deleteFromFile(String string, String dataLine) {
String data = readFromFile(string, null);
data = data.replaceAll(dataLine, "");
writeToFile(string, data, false, false);
}
public static boolean writeToFile(String fileName, String dataLine,
boolean isAppendMode, boolean isNewLine) {
if (isNewLine) {
dataLine = "\n" + dataLine;
}
try {
File outFile = new File(fileName);
DataOutputStream dos;
if (isAppendMode) {
dos = new DataOutputStream(new FileOutputStream(fileName, true));
} else {
dos = new DataOutputStream(new FileOutputStream(outFile));
}
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
/*
* Reads data from a given file
*/
public static String readFromFile(String fileName, String dataLine2) {
String DataLine = "";
String fileData = "";
try {
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(inFile)));
if (dataLine2 != null)
{
while ((DataLine = br.readLine()) != null)
{
if (DataLine.contains(dataLine2)) {
fileData = DataLine;
}
}
}
else
{
while ((DataLine = br.readLine()) != null)
{
fileData = fileData + "\n" + DataLine;
//System.out.println(DataLine);
}
}
br.close();
}
catch (FileNotFoundException ex)
{
return (null);
} catch (IOException ex)
{
return (null);
}
return (fileData);
}
public static boolean isFileExists(String fileName) {
File file = new File(fileName);
return file.exists();
}
}
You can wrap your logic in a while loop which terminates when a given boolean is true, therefore you will keep going back to the start after each operation is performed. For example:
boolean isRunning = true;
while (isRunning) {
//your code here
if (s2.equals("5")) {
isRunning = false;
}
}
You should also move all of your logic out of main() and into its own seperate function that is called from main(). I'm also not sure why you are writing to a .bat file? Change the extension to .dat if you want to write to a .dat file.
I guess you just want a general code review. Here are my thoughts:
1. Scanner is much easier to use for console input because you can specify input types, such as nextInt(). To initialize it, just use
Scanner sc = new Scanner(System.in);
You can use the same Scanner for every user input in the course of the program. Also, remember to call Scanner.close() before your program exits.
2. Initialize your BufferedReader as follows:
// file is a String variable
BufferedReader in = new BufferedReader(new FileReader(file));
Analogously, read files as follows:
BufferedWriter br = new BufferedWriter(new BufferedReader(file));
3. To keep the program running, practice implementing a do-while block:
boolean quit = false;
do {
// loop program; when user is finished, set quit = true
} while (!quit)
4. For the conditionals based on "Please select the required operations", practice implementing a switch block.
5. Separate the logic for parsing the user input and the logic for operating on the address book by making the console interface a separate class, say, AddressBookUI. When it is runs, it should immediately create an instance of the AddressBookOperations class, and call appropriate methods from there based on user input - AddressBookOperations should have a separate method for each operation (this will also make your switch quite short). It should also have the following private (but not static) variables to store the filename and BufferedRead/Writer. The class should have a constructor with an String filename argument which initializes these variables.
6. Deleting specific lines in files is rather tricky in Java. Try this:
Create a BufferedReader for the file.
Create a new temporary file, and create a BufferedWriter for it.
Read the file line by line. For each line, if it is not the line you want to delete, write it to the temporary file.
Close the reader and the writer
Delete the old file
Rename the temp file to the filename.

Reading and displaying data from a .txt file

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Categories

Resources