Read/Write to an external .txt file using jar file - java

im a newbye and this is my first post. Ive made a game aplication on eclipse that works perfectly. It uses a few .txt files for scores and player options.
The problem is when i try to export it as runnable jar file, well that's the problem, it makes a jar file and makes it impossible for me to write on any of the .txt files i have. I know this because ive tried, well not hundreds but getting close, of solutions and some of which allowed me to read the files but still i cant write on them. I realize this is the normal functioning of a jar file, so my questions are:
How can i have/make an external folder to the jar file in the same directory containing all my txt files? So that it can read and write in those files, and, what methods should i use in my existing code?
Im only showing how i read/write one of those files, but its the same for every other file and im also showing some of the comment on other past solutions:
private final String cubesScore = "resF\\score.txt";
//private final String cubesScore = "/score.txt";
//private final String cubesScore = "//resF//score.txt";
try{
/*
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
*/
Scanner scanner = new Scanner(new File(cubesScore));
//InputStream source = this.getClass().getResourceAsStream(cubesScore);
//Scanner scanner = new Scanner(source);
/*
InputStream inputStream = this.getClass().getResourceAsStream(cubesScore);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputReader);
*/
int value;
int i = 0;
while(scanner.hasNext()){
value = scanner.nextInt();
if(value >= 0){
mostCubesDestroyed[i] = value;
System.out.println(value);
}
else
System.out.println("File corrupted");
++i;
}
scanner.close();
} catch (NullPointerException | FileNotFoundException e) {
System.out.println("File Not Found/Null");
}
write:
try {
PrintWriter out = new PrintWriter(cubesScore);
//OutputStream out = this.getClass().getResourceAsStream(cubesScore);
//out = new PrintWriter(out);
//BufferedWriter out = new BufferedWriter(new FileWriter(cubesScore));
//out.write(mostCubesDestroyed[0]);
//out.newLine();
out.println(mostCubesDestroyed[0]);
System.out.println(mostCubesDestroyed[0]+" Cubes GameMode 0");
//out.write(mostCubesDestroyed[1]);
//out.newLine();
out.println(mostCubesDestroyed[1]);
System.out.println(mostCubesDestroyed[1]+" Cubes GameMode 1");
//out.write(mostCubesDestroyed[2]);
//out.newLine();
out.println(mostCubesDestroyed[2]);
System.out.println(mostCubesDestroyed[2]+" Cubes GameMode 2");
//out.write(mostCubesDestroyed[3]);
//out.newLine();
out.println(mostCubesDestroyed[3]);
System.out.println(mostCubesDestroyed[3]+" Total Cubes Destroyed");
out.close();
} catch (IOException e) {
System.out.println("Error, try again!!");
}
i realize keeping the commented code makes it slightly harder to read but still i wanted to show you some things ive tried...
ive also tried to create the file the first time the app runs but to no success:
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
so thats my problem, if anyone been here before and somehow managed to find a solution or you simply know how to produce the desired result, which is to read/write on a .txt file external to the jar(because internal leads to all sorts of issues) then pls tell me what i should do, ive seen more then a hundred post and videos and still couldnt find the desired solution.
Edit: This has been resolved below, turns out i needed a . on "/score.txt" well a . in all files.

Did you try this?:
private final String CUBES_SCORE = "./score.txt";
if you want it in a subdirectory, you have to create the subdirectory also.
Also, take a look at this: How do I create a file and write to it in Java?

I think there is some problem in your path
private final String cubesScore = "..\resF\score.txt";
hope it helps :)

Related

Java FileReader FileNotFoundException

I am simply trying to read a file, my class file exist in the exact same directory as the file I'm trying to read. The file I'm trying to read is called profiles.txt. I have done the exact same method before In extremely similar circumstances and it worked (and still does work), I have no idea why this doesn't. If anyone could explain I would be very grateful.
public static void readProfiles(BST tree) {
try {
BufferedReader getData = new BufferedReader(
new FileReader(
new File("profiles.txt")));
String data = getData.readLine();
while(data != null) {
String[] profileData = data.split(",");
String[] interests = profileData[7].split(";");
tree.insertProfile(new Profile(
profileData[0],
new int[] {Integer.parseInt(profileData[1]), Integer.parseInt(profileData[2]), Integer.parseInt(profileData[3])},
profileData[4],
profileData[5],
profileData[6],
interests
));
data = getData.readLine();
}
getData.close();
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}
catch(IOException e) {
System.out.println("IO error occured");
System.exit(0);
}
}
The filename is relative and contains no directories, so it needs to be in the current working directory.
Where the class file is has nothing to do it whatsoever.
Try the path relative to the main run file of your program.

Android App: FileNotFound error when file exists

I'm running into a filenotfound when trying to read a file in internal storage; I'm pretty darn sure the file exists where I expect it and with appropriate permissions
I'm creating an android app where I'm saving off a string array list into files on the app's internal storage and then trying to randomly access the various lines from the file. I'm writing the file and reading the file within the same class, so I feel like I shouldn't have issues with like filepath and naming conventions.
Things I've verified or tried:
I've opened the files from the Android Device Monitor and the
contents and location are as expected.
The file permissions are -rw-rw----
I've grabbed the user.dir in both the read and write method and they both return "/" which seems incorrect, but the write method works (since the file is there)
Checked a ton of examples to double check formatting (for filename and for method use)
Read the File java reference texts as well as the android storage reference text
file name with and without ".txt"
I feel like I could probably hard code in the path but that sounds like a bad plan and shouldn't be necessary
Anyway here's wonderwall (or rather my code, but only the code parts that seemed relevant)
final List<String> affirmList = copyFilesToList("affirmation_file.txt");
final List<String> suggestList = copyFilesToList("suggestion_file.txt");
//copyFilesToList tries to open the file via selectSuggestion, if it is empty or fails, it goes into the create method
//opens both files and unpacks them into array list, feeds to unpack mehtods
private List<String> copyFilesToList(String fileName) {
String line="";
List<String> arr = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while ((line = bufferedReader.readLine()) != null) {
arr.add(line);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
arr.add("IO exception");
} finally {
//close stream
}
//test if arr contains something
//if not send to addDefaultLines
if (arr.isEmpty()){
arr = addDefaultLines(fileName);
}
return arr;
}
//
private List<String> addDefaultLines(String fileName){
List<String> arr = new ArrayList<String>(); //create arraylist
if (fileName=="affirmation_file.txt") {
//load affirmation values into arraylist
arr.add("affirmation 1");
arr.add("affirmation 2");
}
if (fileName=="suggestion_file.txt"){
//load suggestion values into arraylist
arr.add("suggestion 1");
arr.add("suggestion 2");
}
//sync arraylist with file
try{
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
String list = "";
int sz=arr.size();
//put the arraylist into a single string, for clarity
for (int i = 0; i < sz; i++) {
list += arr.get(i) + "\n"; //append with line breaks between
}
fos.write(list.getBytes());
}
catch (java.io.IOException e) {
e.printStackTrace();
}
return arr;
}

try catch cannot read file

Im running this method but for some reason I am not able to find the data record, it keeps going to the catch. Can somebody let me know where I am messing up please. I have the data.txt file in the same directory as the java file.
public static Games[] gamesRecord(){
Games[] game = new Games[50];
try{
Scanner dataFile = new Scanner(new File("data.txt"));
for(int i = 0; i > 50; i++){
game[i].title = dataFile.next();
game[i].releaseDate = dataFile.nextInt();
game[i].redistributions = dataFile.nextInt();
game[i].platformRelease = dataFile.next();
}
}catch(FileNotFoundException e){
System.out.println("File data.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
return game;
}
solve issue by placing full path of the file

How to read an external text file from jar

I have a text file that gets written to a network folder and I want my users to be able to click on a jar file which will read in the text file, sort it, and output a sorted file to the same folder. But I'm having trouble formatting the syntax of the InputStream to read the file in.
When I use a FileReader instead of an InputStreamReader the following code works fine in eclipse, but returns empty when run from the jar. When I change it to InputStream like my research suggests - I get a NullPointerException like it can't find the file.
Where did I go wrong? :)
public class sort {
/**
* #param args
*/
public static void main(String[] args) {
sort s = new sort();
ArrayList<String> farmRecords = new ArrayList<String>();
farmRecords = s.getRecords();
String testString = new String();
if(farmRecords.size() > 0){
//do some work to sort the file
}else{
testString = "it didn't really work";
}
writeThis(testString);
}
public ArrayList<String> getRecords(){
ArrayList<String> records = new ArrayList();
BufferedReader br;
InputStream recordsStream = this.getClass().getResourceAsStream("./input.IDX");
try {
String sCurrentLine;
InputStreamReader recordsStreamReader = new InputStreamReader(recordsStream);
br = new BufferedReader(recordsStreamReader);
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return records;
}
private static void writeThis(String payload){
String filename = "./output.IDX";
try {
BufferedWriter fr = new BufferedWriter(new FileWriter(filename));
fr.write(payload);
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
getResourceAsStream() loads files from the classpath. If you are running this from the command line, you would need the current directory (.) on the classpath. If you want to load arbitrary files from the file system, you should use FileInputStream (or FileReader to save having to subsequently wrap the input stream in a reader).
Using a FIS to get a file inside a jar will not work since the file is not on the file system per se. You should use getResrouceAsStream() for that.
Also, to access a file inside a jar, you must add an "!" to the file path. Is the file inside the jar? If not, then try a script to start the jar after passing the classpath:
start.sh
java -cp .:your.jar com.main.class.example.run
Execute this script (on linux) or modify it as per your platform.
Also, you can use the following code to print out the classpath. This way you can check whether your classpath contains the file?
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
// Get the URLs
URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
for (int i = 0; i < urls.length; i++) {
System.out.println(urls[i].getFile());
}
}

delete a file in java does not work

i put this code,which i got from the internet, in my java program but when i try to delete, the original file cannot be deleted and the temporary file cannot be renamed to the original file.The two files remains in the folder with its contents unchanged.
...
public class FilingDatabase {
public static void main(String[]args)throws IOException{
(new FilingDatabase()).run();
FilingDatabase fd=new FilingDatabase();
String word = null;
fd.delete("person.txt",word);
}
.
public void run() throws IOException{
File file=new File("person.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
while((str=br.readLine())!=null)
i++;
System.out.print("\t\t\t\t\t\t***************WELCOME*****************");
System.out.println();
System.out.println("1. Add \n2. Edit \n3. Delete \n4. Exit");
System.out.print("\nEnter option number: ");
option=in.next();
while(true){
...
else if(option.charAt(0)=='3'){
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
}
...
}
}//end of fxn run()
....
public void delete(String file, String lineToRemove) throws IOException{
try {
File inFile = new File(file);
if (!inFile.isFile()){
System.out.println("File does not exist");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
//Scanner br=new Scanner(file);
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm not sure where you're trying to delete, but on the last line of your main:
fd.delete("person.txt",word);
will not delete anything because Object.equals(null) should always return false. (word is null.)
If you're trying to delete inside your loop:
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
It won't delete anything because the delete line is commented out.
I'm not sure what to tell you about deleting and renaming the files, because that works for me.
I'm not going to try to get my head around your code ... and what it is trying to do. (Have you heard of comments? Javadocs? Have you considered using them?)
However, I'd like to point out that both delete and rename can fail under a number of circumstances. In the delete case, these include the following:
the target file does not exist
the target file does exist but the application doesn't have permission to access the parent directory and/or delete the file
the target object is a directory not a file
(on some platforms) the target file is locked because this application or another one currently has it open.
In the case of rename, you have to consider the existence, permissions, etc of the file being renamed (and its parent directory) and the directory you are trying to move. And there's also the issue that rename doesn't work between different file systems.
It is unfortunate that these methods (on the File class) don't say why the delete or rename failed. (The methods on the new Java 7 Files class do ...) Even if they were able to do this, the diagnostics would be limited by what the OS syscalls report. In the case of Unix / Linux, this is pretty limited.

Categories