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.
Related
I cant get rid of this FileNotFound error even though the file exists. Any ideas? (There are hundreds of lines of code so im just going to paste the chunk around the error, if this is an issue I can post more)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
Probably your Windows does not show file extensions; nameList.txt?
Otherwise the working directory is not in the project directory with subdirectory src.
A FileReader uses the default Charset, so the file is not portable. If you run the application on another platform then the developer's, the encoding is wrong.
Best use UTF-8, full Unicode.
Then the reading strips the line ending:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
You could do:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource("/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
If it is a read-only file, stored in the application jar, it is a resource rather than a disk File.
Maybe you are not in the folder you think.
Create a file with a dummy name and get the absolute path of this file, this way you can doublecheck you are where you think you really are.
I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.
So the problem is I try to read the configuration file that is packed inside the .jar which works fine but then when it comes to writing to the file the file can not be found yet they are using the same
getClass().getResource(Path);
it only seems to work with the input stream.
Here is all the code of my IO class.
package com;
public class IO {
public boolean CheckStream () {
String LineRead;
try {
InputStream IS = getClass().getResourceAsStream("Config.txt");
InputStreamReader ISR = new InputStreamReader (IS,Charset.forName("UTf-8"));
BufferedReader BR = new BufferedReader(ISR);
if ((LineRead = BR.readLine()) != null) {
BR.close();
return true;
}
IS.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void Write (String Path, String [] ThingsToWrite) throws FileNotFoundException {
OutputStream Out = new FileOutputStream (getClass().getResource(Path).getPath());
PrintStream PS = new PrintStream (Out);
for (int i = 0; i < ThingsToWrite.length; i ++) {
PS.print(ThingsToWrite[i]);
}
PS.close();
}
}
Any Help is greatly appreciated thanks.
You can't just write to a file within a jar file - it's not a file in the regular sense.
While you could unpack the whole jar file, write the new content, then pack it up again, it would be better to redesign so that you don't need to update the jar file.
For example, you might have a regular local file which is used if it's present, but then fall back to reading from the jar file otherwise. Then you only need to write to the local file.
Goal: to read contents of a file that is in my root directory. Eventually I want to be able to read a .conf file, but right now I am testing with a .txt file since it seems easier to begin with..
I am using the open source Shell file from an XDA video to navigate to my root directory. For reference, the file is located at: "/data/misc/joke.txt"
This is the code in my main method:
String command[]={"su","-c","ls /data/misc"};
Shell shell = new Shell();
String output = shell.sendShellCommand(command);
try {
read(output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So basically all that is doing is granting SU permission, and then navigating to the /data/misc folder. Then in the Shell() class, I scan through each file and search for the text file I want. This might be redundant since I expect the text file to be "joke.txt" EVERYTIME. Anyways, I am having an issue with this block of code, the read() method:
public void read(String out) throws Exception{
File yourFile = new File("/data/misc", out);
FileReader file = new FileReader(yourFile);
BufferedReader reader = new BufferedReader(file);
String line;
String text = "";
line = reader.readLine();
while (line != null) {
text += (line);
line = reader.readLine();
}
setNewTextInTextView(text);
}
It crashes at this line:
FileReader file = new FileReader(yourFile);
Any tips?
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());
}
}