How to convert InputStream to FileInputStream - java

I have this line in my program :
InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");
But how can I get FileInputStream from it [Resource_InputStream] ?

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

Long story short:
Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Related

InputStream's FileInputStream in Java

Is this a correct way to open a "mat1.txt" file, because eclipse IDE is giving error?
InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt");
Error:
Unhandled exception type FileNotFoundException
From the error, it is not able to locate the file but I have placed it in the path as provided. (see below)
Is it due to access permissions in C drive?
I see that you wrote eclipseworkspace but in the path there is a minus sign: eclipse-workspace.
try this:
InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt");
You should wrap your file access with try catch! The following try catch construct uses also the auto close feature! https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt")) {
// consume your InputStream
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

File is not readable after file.setReadable(true)

I try to read the file and get FileNotFoundExeption.
File file = new File("News.out");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
try{
in.readObject();
}
I check, that the file really exists in the directory and check "readable" property of the file.
Then I added programmatical setting of "readable" and "writable" properties
file.setReadable(true);
file.setWritable(true);
System.out.println(file.canRead());
System.out.println(file.canWrite());
And got in logs false, false.
What may be the reason of this?
EDIT:
I tried JSR 203 and use this code:
Path path = FileSystems.getDefault().getPath(filename);
try(
final InputStream in = Files.newInputStream(path);
) {
ObjectInputStream objectInputStream = new ObjectInputStream(in);
newsStorage.setEntities((ArrayList<News>) objectInputStream.readObject());
} catch (NoSuchFileException e) {
createFile(path, filename);
handleException(e);
}
And createFile() method:
private void createFile(Path path, String string) {
try {
Files.newOutputStream(path, StandardOpenOption.CREATE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
File was not created.
Do I understand correctly, that
Files.newOutputStream(path, StandardOpenOption.CREATE);
should create a file?
Do yourself a favor and drop File. Use JSR 203 instead.
Try and use:
try (
final InputStream in = Files.newInputStream("News.out");
) {
// work with "in" here
}
If you can't perform the opening then you will at least have an exception telling you what exactly is wrong, something File has never been able to do.
After that, if you want to set permissions on the file, you can also do so with JSR 203 but that depends on the capabilities of the underlying filesystem. If your filesystem is POSIX compatible then you may use this method for instance. But it also may be that you cannot modify the permissions of the file either.

Java convert inputStream to URL

How can I convert an inputStream to a URL? Here is my code:
InputStream song1 = this.getClass().getClassLoader().getResourceAsStream("/songs/BrokenAngel.mp3");
URL song1Url = song1.toUrl(); //<- pseudo code
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
p = Manager.createPlayer(ml);
p.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am not sure you really want to do this. If you need URL for your specific task just do the following:
URL url = this.getClass().getClassLoader().getResource("/songs/BrokenAngel.mp3");
If however you retrieve input stream in one part of you code, then pass it to another module and there want to find what was the source URL for this input stream it is "almost" impossible. The problem is that you get BufferedInputStream that wraps FileInputStream that does not store the information about it source. You cannot retrieve it even using reflection. If you really want to do this you can do the following.
implement you own UrlInputStream extends InputStream the gets into constructor URL, stores it in class varible, creates input stream by invocation of url.openStream() and wraps it.
Now you can use your stream as usual input stream until you have to retrieve the URL. At this point you have to cast it to your UrlInputStream and call getUrl() method that you will implement.
Note that this approach requires the mp3 to be within your application's sub-directory called songs. You can also use relative pathing for the /songs/BrokenAngel.mp3 part (../../ or something like that. But it takes your applications directory as base!
File appDir = new File(System.getProperty("user.dir"));
URI uri = new URI(appDir.toURI()+"/songs/BrokenAngel.mp3");
// just to check if the file exists
File file = new File(uri);
System.out.println(file.exists())
URL song1Url = uri.toURL();
I think what you want is ClassLoader.findResource(String)
That should return a properly formatted jar:// URL. I haven't tested it myself though, so beware
Try this
URI uri = new URI("/songs/BrokenAngel.mp3");
URL song1Url = uri.toURL();
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
p = Manager.createPlayer(ml);
p.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();

Strange error reading files from a directory in Java

EDIT: children is an array of directories. This code loops trough this array in order to enter to each directory and load into the array webs all the files listed. Then, for each file, the readFile function is supposed to read the file.
My code is:
for (File cat: children) {
File[] webs = cat.listFiles();
System.out.println(" Indexing category: " + cat.getName());
for (File f: webs) {
Web w = readFile(f);
// Do things with w
}
}
I'm getting this error:
org.htmlparser.util.ParserException: Error in opening a connection to 209800.webtrec
209801.webtrec
...
422064.webtrec
422071.webtrec
422087.webtrec
422089.webtrec
422112.webtrec
422125.webtrec
422127.webtrec
;
java.io.IOException: File Name Too Long
at java.io.UnixFileSystem.canonicalize0(Native Method)
at java.io.UnixFileSystem.canonicalize(UnixFileSystem.java:172)
at java.io.File.getCanonicalPath(File.java:576)
at org.htmlparser.http.ConnectionManager.openConnection(ConnectionManager.java:848)
at org.htmlparser.Parser.setResource(Parser.java:398)
at org.htmlparser.Parser.<init>(Parser.java:317)
at org.htmlparser.Parser.<init>(Parser.java:331)
at IndexGenerator.IndexGenerator.readFile(IndexGenerator.java:156)
at IndexGenerator.IndexGenerator.main(IndexGenerator.java:101)
It's strange because I don't see any of those files in that directory.
Thanks!
EDIT2: This is the readFile function. It loads the contents of the file into a string and parses it. Actually, files are html files.
private static Web readFile(File file) {
try {
FileInputStream fin = new FileInputStream(file);
FileChannel fch = fin.getChannel();
// map the contents of the file into ByteBuffer
ByteBuffer byteBuff = fch.map(FileChannel.MapMode.READ_ONLY,
0, fch.size());
// convert ByteBuffer to CharBuffer
// CharBuffer chBuff = Charset.defaultCharset().decode(byteBuff);
CharBuffer chBuff = Charset.forName("UTF-8").decode(byteBuff);
String f = chBuff.toString();
// Close imputstream. By doing this you close the channel associated to it
fin.close();
Parser parser = new Parser(f);
Visitor visit = new Visitor();
parser.visitAllNodesWith((NodeVisitor)visit);
return new Web(visit.getCat(), visit.getBody(), visit.getTitle());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Okay, finally I got the solution.
It was a very stupid error. I had a file in that directory that contained the names of all empty html files that I had deleted in a previous task. So, I was trying to parse it, and then the parser would interpret it like an URL and not as an htmlfile (since there aren't tags and a lot of points...). I couldn't find the file easily because I have millions of files in that folder.

How can I read and print a file in eclipse with relative paths?

I'm trying to read a file in eclipse and print it. The problem is that the compiler always says to me that the file or directory doesn't exist. I have to use relative paths.
The relevant part of the project routes is:
uva.pfc.refactoringEngine.core <--Project
...
src
uva.pfc.refactoringengine.core.actions <-- Actual Package
...
CreateEnumSetPlusClas.java <--File from I want to read the EnumSetPlus.java file
...
EnumSetPlus.java <-- File I want read and print
This is the code:
String total="";
File actual = new File("src/EnumSetPlus.java");
FileReader filereader = null;
try {
filereader = new FileReader(actual);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
BufferedReader input = new BufferedReader(filereader);
try {
while ((line = input.readLine()) != null)
{
total += line + "\n";
}
input.close();
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
System.out.println(total);
I think the problem is that I have to do something if I want the file path recognised by de eclipse project.
Could you help me??
Thaks beforehand.
I'd use getClass().getResourceAsStream("/EnumSetPlus.txt") - this will look for the file on the root of the classpath (which is bin/, but all files from src go to bin). You then get an InputStream which you can adapt to Redaer via new InputStreamReader(stream, encoding)
In Eclipse the current working directory is src by default.
Try this
File actual = new File("EnumSetPlus.txt");
Also I would look into Kevin's answer too. :-)
Try:
String filePath = "/EnumSetPlus.java";
File actual = new File(ClassLoader.getSystemResource(filePath).getFile());
Your example says that you want to read a file called EnumSetPlus.java but the source code is looking for a file called EnumSetPlus.txt.

Categories

Resources