In short what I am trying to do is create a file which is called unSorted.txt and then put random number in it but I want the file to be saved in the desktop. I get an error that says file not found everytime i try to implement filepath(please see code for more reference) in the filewriter.
try {
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
String filePath = desktopPath + File.separator + "unSorted.txt";
File myFile = new File(filePath);
if (myFile.createNewFile()) {
FileWriter myWriter = new FileWriter(filePath);
Random rand = new Random();
for (int i = 0; i < 500; i++) {
int random = rand.nextInt(1000) + 1;
myWriter.write(random + System.lineSeparator());
}
myWriter.close();
}
} catch (IOException e) {
System.err.println("An error occurred. Please try again.");
e.printStackTrace();
}
As you can see from the code, I have implemented File myFile = myFile since the error i get from filewriter is file not found so i decided to create the file first
Here is the error that i am getting:
An error occurred. Please try again.
java.io.IOException: The system cannot find the path specified
at java.base/java.io.WinNTFileSystem.createFileExclusively0(Native Method)
at java.base/java.io.WinNTFileSystem.createFileExclusively(WinNTFileSystem.java:645)
at java.base/java.io.File.createNewFile(File.java:1045)
at AlgorithmUI.generateUnsortedClicked(AlgorithmUI.java:125)
at AlgorithmUI$3.actionPerformed(AlgorithmUI.java:91)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2314)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:407)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6620)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3398)
at java.desktop/java.awt.Component.processEvent(Component.java:6385)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4995)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4827)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4827)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:775)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:720)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:714)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:98)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:747)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:744)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I have added the full code which may help us better understand the problem.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Random;
public class AlgorithmUI {
private JButton bSort;
private JPanel panel;
private JFrame frame;
public AlgorithmUI() {
frame = new JFrame("Algorithm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
bSort = new JButton("Sort");
JButton bSearch = new JButton("Search");
Dimension buttonSize = new Dimension(120, 50);
bSort.setPreferredSize(buttonSize);
bSearch.setPreferredSize(buttonSize);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.CENTER;
panel = new JPanel(new GridBagLayout());
panel.add(bSort, gbc);
gbc.gridy = 1;
panel.add(bSearch, gbc);
frame.getContentPane().add(panel);
frame.setVisible(true);
// Event listeners
bSort.addActionListener(e -> clickedSort());
}
private void removeContent() {
panel.removeAll();
panel.revalidate();
panel.repaint();
}
private void clickedSort() {
removeContent();
JButton openFile = new JButton("Open unSorted File");
JButton generateUnsorted = new JButton("Generate Unsorted Numbers");
GridBagConstraints newgbc = new GridBagConstraints();
newgbc.gridx = 0;
newgbc.gridy = 0;
newgbc.insets = new Insets(10, 10, 10, 10);
newgbc.anchor = GridBagConstraints.CENTER;
panel.setLayout(new GridBagLayout());
panel.add(openFile, newgbc);
newgbc.gridy = 1;
panel.add(generateUnsorted, newgbc);
panel.revalidate();
panel.repaint();
openFile.addActionListener(e -> openFileClicked());
generateUnsorted.addActionListener(e -> generateUnsortedClicked());
}
private void openFileClicked() {
JFileChooser fileChooser = new JFileChooser();
int choice = fileChooser.showOpenDialog(panel);
try {
if (choice == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void generateUnsortedClicked() {
try {
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("user.home"))
.append(File.separator)
.append("Desktop")
.append(File.separator)
.append("unSorted.txt");
String filePath = sb.toString();
System.out.println("Generated file path: " + filePath);
File myFile = new File(filePath);
System.out.println(myFile.getPath());
if (myFile.createNewFile()) {
FileWriter myWriter = new FileWriter(filePath);
Random rand = new Random();
for (int i = 0; i < 500; i++) {
int random = rand.nextInt(1000) + 1;
myWriter.write(random + System.lineSeparator());
}
JOptionPane.showMessageDialog(null, "Generated 500 unsorted integers. Please check your desktop for the file.");
} else {
JOptionPane.showMessageDialog(null, "File already exists. Please delete or rename the existing file before generating a new one.");
}
} catch (IOException e) {
System.err.println("An error occurred. Please try again.");
e.printStackTrace();
}
}
public static void main (String[]args){
SwingUtilities.invokeLater(AlgorithmUI::new);
}
}
You are missing one bracket in your code example, but this code does work.
The first time you run it you will create a new file at the filepath specified. The second time you run the code it will detect the file is present and exit out of the if block. If you are having issues executing please include the error and stacktrace. If you are not happy with how the code functions, please ask more questions.