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.
Related
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 :)
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;
}
So, here's the problem: I'm working on a Java program that reads from a .csv file, and constructs objects out of it. I'm using InputStream, InputStreamReader, and BufferedReader to read the file. The IDE I'm using is NetBeans and the file being read is in the src directory. A quick note, for your convenience, I hardcoded the filename, so that you would understand how it's actually being read. In my actual program, the filename is being passed in as a parameter of the method. Anyways, it seems to work fine in the IDE. But when I create a JAR, it doesn't do what I want it to do.
public void readFile(filename) throws IOException, FileNotFoundException {
is = getClass().getResourceAsStream("file.csv");
isr = new InputStreamReader(is);
//fr = new FileReader(filename);
br = new BufferedReader(isr);
String info;
while ((info = br.readLine()) != null)
{
String[] tokens = info.split(",");
Object object = new Object();
object.setProperty(tokens[0]);
object.setAnotherProperty(tokens[1]);
object.setSomeOtherProperty(tokens[2]);
}
}
catch (FileNotFoundException f)
{
f.getMessage();
}
catch (IOException ioe)
{
ioe.getMessage();
}
catch (ArrayIndexOutOfBoundsException oob)
{
//;
}
catch (NullPointerException npe)
{
//;
}
finally
{
br.close();
isr.close();
is.close();
}
My method to update the file looks like this(once again, the filename has been hardcoded so you could better understand what's going on):
public void updateRoom(String filename, String property1, string property2, string property3) throws FileNotFoundException
{
for (Objects o : objects)
{
if (o.getProperty().equals(property1))
{
o.setProperty(property1);
o.setAnotherProperty(property2);
o.setSomeOtherProperty(property3);
}
}
File file = new File("file.csv");
PrintWriter pr = new PrintWriter(file);
for (Object o : objects)
{
pr.println(o.getProperty() + "," +
o.getAnotherProperty() + "," +
o.getSomeOtherProperty())
}
pr.close();
}
The problem is that the .JAR reads the file when I run it, but instead of writing to the SAME file, it simply creates a new one and writes to that one. It's a problem because every time I run the program again, the properties and values remain unchanged. It's NOT reading from the newly-created file. It's still reading from the original file, but it's writing to a new file.
I want to READ AND WRITE to the same file. That way, if I close the program and run it again, it will have the new properties/values already loaded in.
I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders.
So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer.
What I need is to be able to use the file with only the path in my workspace.
If I just put in the path, which is in the workspace it won't work.
This is how my class File looks like.
public class FileUtil {
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
return returnValue;
}
public void writeTextFile(String fileName, String s) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(s);
}
finally {
output.close();
}
}
}
I hope someone knows what to do.
Thanks!
I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.
Your project is root folder here and images as resources folder from where you can access the file using relative path.
// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));
// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt")));
If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));
This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.
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());
}
}