Scanner, Select File on Computer - java

Now, I read my .txt file by telling where is this file.
I want to change to I can select a file on my computer. How can I do that?
Scanner file = new Scanner(new File("Sample.txt"));
while (file.hasNextLine()) {
String input = file.nextLine();
}

Here is a runnable you can try. Like #Verity has stipulated, use the JFileChooser. Read the comments within the following code:
public class JFileChooserWithConsoleUse {
public static void main(String[] args) {
// A JFrame used here as a backbone for dialogs
javax.swing.JFrame iFrame = new javax.swing.JFrame();
iFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
iFrame.setAlwaysOnTop(true);
iFrame.setLocationRelativeTo(null);
String selectedFile = null;
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new java.io.File("C:\\"));
fc.setDialogTitle("Locate And Select A File To Read...");
int userSelection = fc.showOpenDialog(iFrame);
// The following code will not run until the
// FileChooser dialog window is closed.
iFrame.dispose(); // Dispose of the JFrame.
if (userSelection == 0) {
selectedFile = fc.getSelectedFile().getPath();
}
// If no file was selected (dialog just closed) then
// get out of this method (which in this demo ultimately
// ends (closes) the application.
if (selectedFile == null) {
javax.swing.JOptionPane.showMessageDialog(iFrame, "No File Was Selected To Process!",
"No File Selected!", javax.swing.JOptionPane.WARNING_MESSAGE);
iFrame.dispose(); // Dispose of the JFrame.
return;
}
// Read the selected file... 'Try With Resources' is
// used here so as to auto-close the reader.
try (java.util.Scanner file = new java.util.Scanner(new java.io.File(selectedFile))) {
while (file.hasNextLine()) {
String input = file.nextLine();
// Display each read line in the Console Window.
System.out.println(input);
}
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
}
}

In this case you need to use an JFileChooser

Related

Comparing ArrayList with user input

I have been trying to compare the file content with user input. The program is reading from a specific file and it checks against the user's string input. I am having trouble comparing the ArrayList with the user input.
public class btnLoginListener implements Listener
{
#Override
public void handleEvent(Event arg0)
{
//variables for the class
username = txtUsername.getText();
password = txtPassword.getText();
MessageBox messageBox = new MessageBox(shell, SWT.OK);
try {
writeFile();
messageBox.setMessage("Success Writing the File!");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when writing the file!");
}
try {
readFile("in.txt");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when reading the file!" + x);
}
if (username.equals(names))
{
messageBox.setMessage("Correct");
}
else
{
messageBox.setMessage("Wrong");
}
messageBox.open();
}
}
private static void readFile(String fileName) throws IOException
{
//use . to get current directory
File dir = new File(".");
File fin = new File(dir.getCanonicalPath() + File.separator + fileName);
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null)
{
Collections.addAll(names, line);
}
br.close();
}
I am assuming you are trying to check whether an element exists in the list. If yes, then you need to use contains method, here's the Javadoc.
So, instead of using if (username.equals(names)), you can use if (names.contains(username)).
Apart from this, you should make the following changes:
Don't read the file every time an event is called. As you are reading a static file, you can read it once and store it in an ArrayList.
Make variables username and password local.
Remove writeFile() call unless it's appending/writing dynamic values on each event.

Saving the font from a text pane java

I'm making a Text Editor as a side project and as of now I'm struggling by saving and loading the text's font letter, color, and decoration; in other words, I can only save a plain text. My question is, how can I save and load all of these?
private void Edit() {//This is the method where the program edits the text
StyledDocument doc = this.tpText.getStyledDocument();
Style estilo = this.tpText.addStyle("miEstilo", null);
StyleConstants.setForeground(estilo, colour); //Color
StyleConstants.setFontFamily(estilo, fontLetter);//Letter
StyleConstants.setFontSize(estilo, size);//Size
StyleConstants.setBold(estilo, bold);//Bold
StyleConstants.setItalic(estilo, italics);//Italics
StyleConstants.setUnderline(estilo, underline);//Underline
doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("miEstilo"), true);//The only text that will be edited is the one that the user highlights
}
private void comboxFontsActionPerformed(java.awt.event.ActionEvent evt) {//This is one of the methods in which the program edits the text
this.fontLetter = (String) this.comboxFonts.getSelectedItem();
Edit();
}
private void mibtnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//Save as... menu item button
int saveResult = fileSelect.showSaveDialog(null);
if (saveResult == fileSelect.APPROVE_OPTION) {
saveFile(fileSelect.getSelectedFile(), this.tpText.getText());
this.mibtnSave.setEnabled(true);
}
}
public void saveFile(File file, String contents) {//Save File
BufferedWriter writer = null;
String filePath = file.getPath();
try {
writer = new BufferedWriter(new FileWriter(filePath));
writer.write(contents);
writer.close();
this.tpText.setText(contents);
currentFile = file;
} catch (Exception e) {
}
}
public void openFile(File file) {//Load File
if (file.canRead()) {
String filePath = file.getPath();
String fileContents = "";
if (filePath.endsWith(".txt")) {
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()) {
fileContents += sc.nextLine();
}
sc.close();
} catch (FileNotFoundException e) {
}
this.tpText.setText(fileContents);
currentFile = file;
} else {
JOptionPane.showMessageDialog(null, "Only .txt files are supported.");
}
} else {
JOptionPane.showMessageDialog(null, "Could not open file...");
}
}
I don't know if i got your question right, but if your trying to save the style besides the plain text you may do the following.
save all style attributes in another file next to the text file and you can restore it when you open the text file.

nullpointerexception error on cancel or closing dialog

My problem is when my showopendialog appears and I press cancel or the X on the right corner instead of loading some text in my textarea, the console shows the error of nullpointexception on my line String filename=f.getAbsolutePath();
My action open is on a menu bar.
Thank you.
JFileChooser flcFile = new JFileChooser("c:\\");
flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
String filename=f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
If you close without selecting a file, you can't get the absolute path of the file. Always check if a file has been selected by the user by checking the value returned by the showOpenDialog() method. Only get the absolute path after this check.
Useful reading: The JFileChooser docs.
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File f = flcFile.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Hello I modified your code, check the following example:
public class Main {
public static void main(String[] args) {
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
if (JFileChooser.CANCEL_OPTION == result) {
System.out.println("canceled");
} else if (JFileChooser.APPROVE_OPTION== result) {
String filename = f.getAbsolutePath();
System.out.println(filename);
}else{
System.out.println(result);
}
}
}
You need to check the return value of the showOpenDialog method in order to know the selected option, I hope it help you
cheers.

How to store text from JOptionPane into text file

I am a novice. I am trying to take the user-input text from the JOptionPane, and store it into a text file. Thereafter I would like to read the text and do what-not with it.
May I please have help on storing the inputted text? Thanks.
Here's my code:
import javax.swing.JOptionPane;
import java.io.*;
public class RunProgram {
public static void introView() {
//The introduction
JOptionPane.showMessageDialog(null, "Welcome." +
" To begin, please click the below button to input some information " +
"about yourself.");
}
public static void personInput() {
try{
File userInfo = new File("C:\\Users\\WG Chasi\\workspace\\" +
"Useful Java\\products\\UserInfo.txt");
userInfo.getParentFile().mkdirs();
FileWriter input = new FileWriter(userInfo);
JOptionPane userInput = new JOptionPane();
userInput.showInputDialog("Enter details");/*I want to store the text from the InputDialog into the text file*/
//Write text from the JOptionPane into UserInfo.txt
}catch(Exception e){
JOptionPane.showMessageDialog(null, "An ERROR has occured.");
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
introView();
personInput();
}
});
}
}
You have any number of potential options, depending on your needs...
You could...
Write the contents to a Properties file...
private Properties properties = new Properties();
//...
String name = JOptionPane.showInputDialog("What is your name?");
properties.set("user.name", name);
//...
protected void savePropeties() throws IOException {
try (OutputStream os = new FileOutputStream(new File("User.properties"))) {
properties.store(os, "User details");
}
}
protected void loadPropeties() throws IOException {
try (InputStream is = new FileInputStream(new File("User.properties"))) {
// Note, this will overwrite any previously existing
// values...
properties.load(is);
}
}
As you can see, you have to physically load and save the contents yourself. This does mean, however, you get to control the location of the file...
You could...
Make use of the Preferences API...
String name = JOptionPane.showInputDialog("What is your name?");
Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
preferences.put("user.name", name);
Then you would simply use something like...
Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
String name = preferences.get("user.name", null);
to retrieve the values.
The benefit of this is the storage process is taking care for you, but you lose control of where the data is stored.
You could...
Write the data to a file yourself, in your own format. This is lot of work and overhead, but you gain the benefit of not only controlling the location of the file, but also the format that the data is maintained in. See Basic I/O for some more details.
Write the data in XML format, which provides a level of hierarchical control (if that's important), but does increase the complexity of the management.
Try this
public static void personInput()
{
String whatTheUserEntered = JOptionPane.showInputDialog("Enter details");
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory( new File( "./") );
int actionDialog = chooser.showSaveDialog(yourWindowName); //where the dialog should render
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File(chooser.getSelectedFile( ) + ".txt" ); //opens a filechooser dialog allowing you to choose where to store the file and appends the .txt mime type
if(fileName == null)
return;
if(fileName.exists()) //if filename already exists
{
actionDialog = JOptionPane.showConfirmDialog(yourWindowName,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION) //open a new dialog to confirm the replacement file
return;
}
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(whatTheUserEntered );
out.close(); //write the data to the file and close, please refer to what madProgrammer has explained in the comments here about where the file may not close correctly.
}
catch(Exception ex)
{
System.err.println("Error: " + ex.getMessage());
}
}
}
I am basically attempting to get the text from the input dialog and write it to a file of your choice. The file will be written as a text file using the appending string ".txt" which sets the mime type so will always be text.
Let me know how it goes.

When writing to file in Java the file cannot be saved in folders

What im trying to do is simply letting the user choose a directory to save a text file to, Problem is im trying to select a folder im creating on my desktop but when i select the folder with the JFileChooser and letting the code i have do the work it's still saved outside the folder and into the desktop.. Why? Can someone please explain what i did wrong so i might learn something..
public class TextFileSaver {
String filePath;//Used in the setPath and getPath methods
String filename = File.separator+"tmp"; //Used for the JFileChoosers directory
public TextFileSaver(){
//Get our file saver to the screen
JFileChooser fc = new JFileChooser(new File(filename));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Only able to select directiories
// Show open dialog; this method does not return until the dialog is closed
fc.showSaveDialog(null);
File selectedLocation = fc.getCurrentDirectory(); //Gets the selected Location
//Sets the path of the file so we can read from it.
setPath(selectedLocation.getAbsolutePath());
FileName();
try {
SaveFile(filePath);
}
catch (IOException ex) {
Logger.getLogger(TextFileSaver.class.getName()).log(Level.SEVERE, null, ex);
//Show a message dialog
JOptionPane.showMessageDialog(null, "The file could not be saved, Please try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setPath(String Path){
filePath = Path;
}
public String getPath(){
return filePath;
}
private void FileName(){
String name = JOptionPane.showInputDialog
("What name do you want to give the file?");
//Temporary code bellow will change to StringBuilder here.
filePath = filePath + "/" + name + ".txt";
}
private void SaveFile(String Path) throws IOException{
System.out.println(Path);
//The outStream that we will use to write to the text file the user is creating.
PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(Path)));
outStream.println("Test text!");
outStream.close();
}
}
All the methods are executed through the constructor.. So the code happends step by step..
Use getSelectedFile() and not getCurrentDirectory() and also, you should append your filePath somewhere.

Categories

Resources