I am trying to create a block that writes a file when the file doesn't exsist, but it has turned into a Catch-22. The file doesn't exist, so it can't write the file so it can exsist. Here is my attempt:
if(!FileReadWrite.file2.exists())
FileReadWrite.fileWrite();
public static File file2 = new File("./settings.txt");
public static void fileWrite()
{
try
{
FileWriter fstream = new FileWriter(file2);
BufferedWriter out = new BufferedWriter(fstream);
String c = Byte.toString(Textures.a);
out.write(c);
out.close();
}catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fin = null;
try
{
fin = new FileInputStream(file2);
while ((ch = fin.read()) != -1)
{
strContent.append((char) ch);
}
fin.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
I am using Eclipse. The file is in the bin folder, but when I export it to a jar it is outside the jar folder.
Exception in thread "main" java.lang.ExceptionInInitializerError
at srcD.Main.<init>(Main.java:19) //(FileReadWrite.fileWrite())
at srcD.Main.main(Main.java:129) //(Make JFrame)
Caused by: java.lang.NullPointerException
at srcD.FileReadWrite.<clinit>(FileReadWrite.java:7) //(public file...)
... 2 more
I think this ClassLoader.getSystemResource("settings.txt") code returns null and .getFile() gets an NPE
Answer to comment
Firstly you should understand that method getSystemResource NOT for outside resources read this
For load outside resources from jar you have to use full path to resource, full != absolute,
how to find full path
start point + path to resource
For example we have next files structure /Users/fakeuser/tetsproject/ - this folder contains your jar and conf folder contains or should contain settings.txt, if you have delivery structure like this your code will be
public static File file2 = new File("./conf/settings.txt");
And that is all.
Related
I am trying to load image file from file directory. Then, I want to convert the file object to string object. Unfortunately, I keep receive this error messages. How can I resolve it?
java.io.FileNotFoundException: E:\workspace\sesaja\Images (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at test.Test1.main(Test1.java:29)
Thi is my overall code
public class Test1 {
public static void main(String args[]){
String s = System.getProperty("user.dir") + System.getProperty("file.separator")+ "Images";
File f = new File (s);
FileInputStream fis = null;
String str = "";
try {
fis = new FileInputStream(f);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
str += (char) content;
}
System.out.println("After reading file");
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Concatenate desired file name at the end of this line:
String s = System.getProperty("user.dir") +
System.getProperty("file.separator")+ "Images" + fileName;
It seems you are trying to read data from a directory, which is not logically correct.
Also using FileInputStream in order to read characters (not data) is not recommended. You may use a BufferedReader instead.
Also for getting name of files inside a directory, you may read this: Read all files in a folder
I have a text file in the same location as my .jar program:
Main Folder:
|_ myJar.jar
|_ myText.txt
When I run the .jar file I would like it to read the contents of myText.txt, however with the path set as String fileName = "./Paths.txt"; it still doesn't read the file. I believe it's trying to read the Paths.txt file from inside the jar.
I tried other solutions, none seem to tell the program to read the Paths.txt file from outside of the jar file, so any help would be greatly appreciated.
Code:
public static void readFile() {
String fileName = "./Paths.txt";
BufferedReader br;
String line;
//Attempts to read fileName
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
try {
// Starts reading the file and adding values to linked hashmap
while ((line = br.readLine()) != null) {
String[] lineSplit1 = line.split("#");
String lineKey = lineSplit1[0];
String lineValue = lineSplit1[1];
hm.put(lineKey, lineValue);
}
} catch(Exception e3) {
errorMessage("Error when trying to read the file and add "
+ "the values to a hashmap");
}
//Attempts to close fileName
try {
br.close();
} catch(IOException e1 ) {
System.out.println("Messed up while trying to close buffered reader");
System.out.println(e1);
}
} catch (FileNotFoundException e1) {
errorMessage("The file " + fileName + " does not exist"
+ "\nI have created the file for you.");
try {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println("");
writer.close();
} catch(Exception e2) {
errorMessage("Error while trying to create " + fileName);
}
}
}
I suppose, you can get a full path to your file, just need to initialize it, via your Class, which should be packaged in myJar.jar. Just change YourClass in the example to some real Class from your jar.
public static void readFile() {
File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String fileName = file.getParent() + File.separator + "Paths.txt";
...
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 need to access a configuration file from within my Jar, so I use:
URL configUrl = Object.class.getResource("/config.xml");
Now I need to convert URL into a File object, because that's what the ConfigurationFile object downstream needs for initialization. When I try this:
new File(configUrl.toURI())
I get:
java.lang.IllegalArgumentException: URI is not hierarchical
When I try this:
new File(Thread.currentThread().getContextClassLoader().getResource("config.xml").getFile())
I get:
File does not exist: 'file:\E:\Apps\jarfile.jar!\config.xml'
NOTE: Unfortunately I must have a File object, on an InputStream.
If file is inside of JAR... you can use getResourceAsStream() and read directly or using URL...
URL urlConfig = Object.class.getResource(CONFIG_FILE);
if (urlConfig == null) {
// throw <error>
}
URLConnection connConfig = urlConfig.openConnection();
InputStream isConfig = connConfig.getInputStream(); // do things
Save content to a temporal File... (wait 1 second... mmm)
public static File doThing(InputStream is) throws IOException {
File tmp = null;
FileOutputStream tmpOs = null;
try {
tmp = File.createTempFile("xml", "tmp");
tmpOs = new FileOutputStream(tmp);
int len = -1;
byte[] b = new byte[4096];
while ((len = is.read(b)) != -1) {
tmpOs.write(b, 0, len);
}
} finally {
try { is.close(); } catch (Exception e) {}
try { tmpOs.close(); } catch (Exception e) {}
}
return tmp;
}
Your question doesn't make sense. A resource may be inside a JAR file, and an item in a JAR file simply is not a file, or a File.
Period.
If you need a File object you are going to have to distribute the item separately from the JAR file.
Have you tried this:
File f;
try {
f = new File(url.toURI());
} catch(URISyntaxException e) {
f = new File(url.getPath());
}
I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.