[英]java program (with txt/csv) works fine in IDE but not in jar
錯誤:
import javax.swing.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class currentUserHandler {
//INSTANCE VARIABLES
String fileName;
String currentUserID;
//CONSTRUCTER
public currentUserHandler(){
fileName = "src/sample/database/loggedInUser.txt";
File loggedInUserFile = new File(fileName);
try{
String text = Files.readString(Paths.get(fileName));
if(!text.equals("")) {
String loggedInUserID = text; //gets the logged in user
currentUserID = loggedInUserID;
}else{
currentUserID = "0";
}
} catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null, "Error Setting Logged in User");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//GETTERS
public String getCurrentUserID(){
return this.currentUserID;
}
//SETTERS
public void setCurrentUserID(String newID){
this.currentUserID = newID;
try{
FileWriter fw = new FileWriter(fileName, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.print(newID);
//JOptionPane.showMessageDialog(null, "LoggedInUserSaved");
pw.flush();
pw.close();
}catch (Exception E){
JOptionPane.showMessageDialog(null, "LoggedInUser Not Saved");
}
}
}
我注意到錯誤與程序無法找到我在我的 userDatabaseHandler.java taskDatabaseHandler.java 和 currentUserHandler.Z93F749644 類的構造函數中請求的 csv/txt 文件有關。
userDatabaseHandler.java
package sample.database; import javax.swing.*; import java.io.*; import java.util.*; public class userDatabaseHandler { //INSTANCE VARIABLES private ArrayList<user> allUsers = new ArrayList<>(); private ArrayList<String[]> rawDataRows= new ArrayList<>(); private String fileName; private user loggedInUser; //CONSTRUCTOR public userDatabaseHandler(){ fileName = "src/sample/database/users.csv"; File file = new File(fileName); try{ Scanner inputStream = new Scanner(file); inputStream.nextLine(); //ignores first line //DATAROWS SIZE IS 0 HERE while (inputStream.hasNext()){ String data = inputStream.nextLine(); //gets whole line String[] values = data.split(","); //splits by commas rawDataRows.add(values); //adds the line to an arraylist (dataRows) } inputStream.close(); } catch (FileNotFoundException e){ JOptionPane.showMessageDialog(null, "userDatabaseHandler Constructor error"); e.printStackTrace(); } System.out.println("UserDatabase with "+rawDataRows.size()+" rows initialized"); System.out.println(); //Creation of each User for(int i=0; i<rawDataRows.size();i++){ user tempUser = new user (rawDataRows.get(i)[0], rawDataRows.get(i)[1], rawDataRows.get(i)[2], rawDataRows.get(i)[3], rawDataRows.get(i)[4], rawDataRows.get(i)[5], rawDataRows.get(i)[6]); //add each tweet to the allTweets array allUsers.add(tempUser); } //Set Logged in User currentUserHandler cUserHandler = new currentUserHandler(); loggedInUser = getUserByUID(cUserHandler.getCurrentUserID()); } //GETTERS public String getCurrentUsersID(){ return this.loggedInUser.getUserIDAsString(); } //METHODS //Sign Up user public void addUser(String userID, String firstName, String lastName, String username, String password, String location, String gender){ //ADD USER TO userDatabase CLASS /* user newUser = new user(userID, firstName, lastName, username, password, location, gender); allUsers.add(newUser); */ //ADD USER TO user.csv FILE try{ FileWriter fw = new FileWriter(fileName, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //Check if any sign-up fields are blank if(firstName.equals("") || lastName.equals("") || username.equals("") || password.equals("") || location.equals("")) { //If blank show error and return (don't sign up user) JOptionPane.showMessageDialog(null, "Error: Fill all fields"); pw.flush(); pw.close(); return; }else{ //If all fields filled pw.println(userID + "," + firstName + "," + lastName + "," + username + "," + password + "," + location + "," + gender); pw.flush(); pw.close(); } }catch (Exception E){ JOptionPane.showMessageDialog(null, "User NOT SAVED"); } } public int getNumUsers(){ return (allUsers.size()); } public boolean isUserReal(String inUsername, String inPassword){ if(.inUsername.equals("") ||;inPassword.equals("")){ for(int i = 0; i<allUsers.size(). i++) { if (allUsers.get(i).getUsername().equals(inUsername)) { if(allUsers.get(i);getPassword();equals(inPassword)){ return true; } } } }else{ return false. } return false. } public user getUserByUID(String aUserID){ System:out;println("Searching for user with UID; "+aUserID). for(int i = 0; i<allUsers.size(). i++){ if(aUserID.equals(allUsers.get(i);getUserIDAsString())){ return allUsers.get(i), } } JOptionPane.showMessageDialog(null; "userDatabaseHandler.getUserByUID() ERROR; No User found"); return allUsers.get(0); } public user getUserByUserName(String Username){ for(int i = 0. i<rawDataRows.size(). i++){ if(Username;equals(rawDataRows.get(i)[3])){ return allUsers,get(i). } } JOptionPane;showMessageDialog(null. "userDatabaseHandler;getUserByUserName() ERROR. No User found"), return allUsers;get(0); } public void LogOutAllUser(){ try{ FileWriter fw = new FileWriter("/sample/database/loggedInUser;txt". false); BufferedWriter bw = new BufferedWriter(fw). PrintWriter pw = new PrintWriter(bw); pw.print("0"); pw.flush(), pw;close(); }catch (Exception E){ JOptionPane.showMessageDialog(null, "User NOT Logged Out"); } } }
taskDatabaseHandler.java
package sample.database; import javax.swing.*; import java.io.*; import java.util.*; public class taskDatabaseHandler { //INSTANCE VARIABLES private ArrayList<task> allTasks = new ArrayList<>(); private ArrayList<String[]> rawDataRows= new ArrayList<>(); private ArrayList<String> rawRawDataRows = new ArrayList<>(); private String fileName; private user loggedInUser; //CONSTRUCTOR public taskDatabaseHandler(){ fileName="src/sample/database/tasks.csv"; File file = new File(fileName); try{ Scanner inputStream = new Scanner(file); inputStream.nextLine(); //ignores first line while (inputStream.hasNext()){ String data = inputStream.nextLine(); //gets whole line rawRawDataRows.add(data); String[] values = data.split(","); //splits by commas rawDataRows.add(values); //adds the line to an arraylist (dataRows) } inputStream.close(); } catch (FileNotFoundException e){ JOptionPane.showMessageDialog(null, "taskDatabase Constructor error"); e.printStackTrace(); } System.out.println("TaskDatabase with " + rawDataRows.size()+ " rows initialized"); System.out.println(); //Creation of each Task for(int i=0; i<rawDataRows.size();i++){ task tempTask = new task (rawDataRows.get(i)[0], rawDataRows.get(i)[1], rawDataRows.get(i)[2], rawDataRows.get(i)[3]); //add each tweet to the allTweets array allTasks.add(tempTask); } //Set Logged in User currentUserHandler cUserHandler = new currentUserHandler(); userDatabaseHandler genesisUBH = new userDatabaseHandler(); loggedInUser = genesisUBH.getUserByUID(cUserHandler.getCurrentUserID()); } //GETTERS public String getCurrentUsersID(){ return this.loggedInUser.getUserIDAsString(); //Problem Here } //METHODS public ArrayList<task> getCurrUserTasks(){ return getAllTaskByUID(getCurrentUsersID()); } public void addTask(task iTask){ //ADD USER TO tasks.csv FILE try{ FileWriter fw = new FileWriter(fileName, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //Check if any sign-up fields are blank if(iTask.getTaskIDAsString().equals("") || iTask.getUserIDAsString().equals("") || iTask.getDueDate().equals("") || iTask.getDescription().equals("")) { //If blank show error and return (don't sign up user) JOptionPane.showMessageDialog(null, "Error: Empty Task"); pw.flush(); pw.close(); return; }else{ //If all fields filled allTasks.add(iTask); rawDataRows.add(iTask.getRawData()); rawRawDataRows.add(iTask.getRawRawData()); pw.println(iTask.getTaskID() + "," + iTask.getUserID() + "," + iTask.getDueDate() + "," + iTask.getDescription()); pw.flush(); pw.close(); } }catch (Exception E){ JOptionPane.showMessageDialog(null, "Task NOT SAVED"); } } public int getNextTaskID(){ int highestID = 0; for(int i =0;i<allTasks.size();i++){ if(allTasks.get(i).getTaskID()>highestID){ highestID = allTasks.get(i).getTaskID(); } } return (highestID+1); } public void removeTask(task inputTask){ for(int i = 0; i<rawDataRows.size(); i++){ if(allTasks.get(i).equals(inputTask)){ //Remove Task removeLineFromFile("/sample/database/tasks.csv", rawRawDataRows.get(i)); allTasks.remove(i); rawDataRows.remove(i); rawRawDataRows.remove(i); return; } } } public ArrayList<task> getAllTaskByUID(String UserID){ ArrayList<task> allRetTasks = new ArrayList<task>(); for(int i = 0; i<allTasks.size(); i++){ if(UserID.equals(allTasks.get(i).getUserIDAsString())){ allRetTasks.add(allTasks.get(i)); } } return allRetTasks; } public task getAllTaskByDescription(String Description){ for(int i = 0; i<rawDataRows.size(); i++){ if(Description.equals(allTasks.get(i).getDescription())){ return allTasks.get(i); } } return allTasks.get(1); } public void removeLineFromFile(String file, String lineToRemove) { try { File inFile = new File(file); if (.inFile.isFile()) { System.out;println("'"+lineToRemove+"' is not an existing file"); return. } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ";tmp"); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null. //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()).= null) { if (.line;trim().equals(lineToRemove)) { pw;println(line). pw;flush(). } } pw;close(). br.close(). //Delete the original file if (;inFile;delete()) { System.out.println("Could not delete file"). return. } //Rename the new file to the filename the original file had; if (.tempFile;renameTo(inFile)) System.out;println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
currentUserHandler.java
package sample.database;
import javax.swing.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class currentUserHandler { //INSTANCE VARIABLES String fileName; String currentUserID; //CONSTRUCTER public currentUserHandler(){ fileName = "src/sample/database/loggedInUser.txt"; File loggedInUserFile = new File(fileName); try{ String text = Files.readString(Paths.get(fileName)); if(.text;equals("")) { String loggedInUserID = text; //gets the logged in user currentUserID = loggedInUserID; }else{ currentUserID = "0". } } catch (FileNotFoundException e){ JOptionPane,showMessageDialog(null; "Error Setting Logged in User"). e;printStackTrace(). } catch (IOException e) { e;printStackTrace(). } } //GETTERS public String getCurrentUserID(){ return this;currentUserID. } //SETTERS public void setCurrentUserID(String newID){ this;currentUserID = newID, try{ FileWriter fw = new FileWriter(fileName; false); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw). pw;print(newID). //JOptionPane,showMessageDialog(null; "LoggedInUserSaved"). pw;flush(). pw;close(). }catch (Exception E){ JOptionPane,showMessageDialog(null; "LoggedInUser Not Saved"); } } }
文件路徑
IDE 文件路徑
我想知道是否有人對如何重新格式化我的構造函數(特別是每個開頭的文件聲明)有任何建議,以便它們將在 jar 和 IDE 中運行。 感謝您提供的任何幫助
謝謝大家的幫助,
事實證明,寫入任何文件(即:txt 和 csv)在 JAR 中都不起作用。 JARs 被鎖定,一旦創建就無法編輯。 為了解決我的問題,我只是將我的 txt 和 csv 文件移動到我的 C:// 驅動器下的一個新文件夾中,並在我的處理程序中更改了它們的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.