r/JavaProgramming • u/XIA_Biologicals_WVSU • 4d ago
This is a little program that I created with the help of AI
This is a little program that I created with the help of AI. I only used AI when I became stuck on certain parts of the program. The program allows the user to input a file directly into the IDE, whcich allows the terminal to output what is in the file; it also allows the user to select a file to read, and finally allows the user to select a place to save a file and enter text to be saved into a file.
import javax.swing.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.awt.Desktop;
import java.util.Scanner;
import static java.awt.SystemColor.
text
;
class newProject {
public static void main(String[] args) throws IOException {
// capture user input:
Scanner scanner = new Scanner(System.
in
);
String UserData = scanner.nextLine();
System.
out
.println(UserData);
if (UserData.equals("1")) {
Files.
lines
(Path.
of
("C:/Users/zgarr/OneDrive/Desktop/text.txt"))
.forEach(System.
out
::println);
} else if (UserData.equals("2")) {
File directory = new File("C://documents");
try {
ProcessBuilder explorer = new ProcessBuilder(
"explorer.exe",
directory.getAbsolutePath()
);
explorer.start();
// User selection for number 2
} catch (IOException e) {
e.printStackTrace();
}
} else if (UserData.equals("3")) {
System.
out
.print("Enter a name for your file");
String fileName = scanner.nextLine();
if (!fileName.endsWith(".txt")) {
fileName += ".txt";
}
String folder =
chooseSaveFolder
();
File fullPath = new File(folder, fileName);
System.
out
.println("Start typing your text to save it. Type exit when finished");
try (FileWriter writer = new FileWriter(fullPath)) {
while (true) {
String line = scanner.nextLine();
if (line.equalsIgnoreCase("EXIT")) {
break;
}
writer.write(line + System.
lineSeparator
());
}
System.
out
.println("saved doucment too " + fullPath);
} catch (IOException e) {
System.
out
.println("Error saving file" + e.getMessage());
}
} else {
System.
out
.println("Wrong selection");
}
scanner.close();
}
// This method helps the user select a place to save the file
public static String chooseSaveFolder() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select a folder to save your file");
chooser.setFileSelectionMode(JFileChooser.
DIRECTORIES_ONLY
);
int result = chooser.showSaveDialog(null);
if (result == JFileChooser.
APPROVE_OPTION
) {
return chooser.getSelectedFile().getAbsolutePath();
}
return ".";
}
}
2
Upvotes