I'm trying to write some text to a file using Files.write() method.
byte[] contents = project.getCode().getBytes(StandardCharsets.UTF_8);
try {
Files.write(project.getFilePath(), contents, StandardOpenOption.CREATE);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
According to the API, if the file doesn't exist, it will be created and then written to.
However, I get this:
java.nio.file.NoSuchFileException: C:\Users\Administrator\Desktop\work\Default.txt
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newOutputStream(Unknown Source)
at java.nio.file.Files.newOutputStream(Unknown Source)
at java.nio.file.Files.write(Unknown Source)
Am I missing something?
You should be able to create a file, but you can't create a directory. You may need to check the directory C:\Users\Administrator\Desktop\work exists first.
You can do
Path parentDir = project.getFilePath().getParent();
if (!Files.exists(parentDir))
Files.createDirectories(parentDir);
The file will be written if default OpenOptions parameter is used. If you specify CREATE, default parameters will not be used, but it is used just CREATE. Try to add WRITE in addition to CREATE, or just leave that parameter empty
Related
Without pasting the entire code here, the line where the exception keeps happening is :
PrintWriter prtwrt = new PrintWriter(new File(directoryName+File.separator+stud.getIndex()+".txt"));
I have consulted the internet, and the books I have on Java, and by all logic it ought to work, but it doesn't. Can someone explain as to why it doesn't work, or perhaps propose a solution?
Stacktrace :
java.io.FileNotFoundException: students\0096-03.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileWriter.<init>(Unknown Source)
at StudentsManager.main(StudentsManager.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Also, directoryName, as the name implies, is the name of the directory where the file should be created. In this case it is "students".
So lets have
File f=new File(directoryName+File.separator+stud.getIndex()+".txt");
First lets check if path exists and create dir tree if it does not:
if(!f.getParentFile().exists()) f.getParentFile().mkdirs();
now you can try to create Writer
PrintWriter prtwrt = new PrintWriter(f);
PrintWriter should create new file if not yet exists; If for some reasons it will not work, create file beforeheand with f.createNewFile()
All together it must work.
try to enter the full path to the file because you might enter a relative path.
If you want to check if you have found the file try the following code:
File file = new File(...);
if(!file.exists()) {
System.out.println("File not found!");
return;
}
I am currently trying to get a list of files in a directory.
When I try to get the filehandle for the directory it says that it is a file, but it isn't. When I then readString() from it, it returns the filenames of the files in it. This only happens in the IDE (Eclipse NEON.2), but when I export to JAR it crashes when I try to run.
How can I get LibGDX to recognise it as a directory and get all files in that directory. One last thing I have seen many anwers saying that list() doesn't work on desktop, but I have also read that it works. Can someone check if this is true or not.
public void loadEnemyBaseTypes(){
ArrayList<FileHandle> enemyBaseFiles = new ArrayList<FileHandle>();
FileHandle enemyBaseDirectory =
Gdx.files.internal("prototypes/enemybases");
System.out.println(enemyBaseDirectory.exists());
System.out.println(enemyBaseDirectory.isDirectory());
String[] fileNames = enemyBaseDirectory.readString().split("\n");
for(int i = 0; i < fileNames.length; i++)
System.out.println(fileNames[i]);
}
IDE Output:
true
false
base_0.enybse
base_1.enybse
base_2.enybse
base_3.enybse
base_4.enybse
base_5.enybse
Terminal Output:
true
false
Exception in thread "LWJGL Application" java.lang.NullPointerException
at java.io.FilterInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.Reader.read(Unknown Source)
at com.badlogic.gdx.files.FileHandle.readString(FileHandle.java:207)
at com.badlogic.gdx.files.FileHandle.readString(FileHandle.java:191)
at dev.thomaslienbacher.simplegame.controllers.EnemyManager.loadEnemyBaseTypes(EnemyManager.java:53)
at dev.thomaslienbacher.simplegame.controllers.EnemyManager.loadAssets(EnemyManager.java:33)
at dev.thomaslienbacher.simplegame.scene.GameScene.loadAssets(GameScene.java:62)
at dev.thomaslienbacher.simplegame.Game.update(Game.java:149)
at dev.thomaslienbacher.simplegame.Game.render(Game.java:134)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
I created nested folder inside Assets list -> enemy then I keep three .png files inside enemy folder having name 1.png, 2.png and 3.png.
FileHandle enemyBaseDirectory = Gdx.files.internal("list/enemy");
System.out.println(enemyBaseDirectory.exists());
System.out.println(enemyBaseDirectory.isDirectory());
FileHandle allList[]=enemyBaseDirectory.list();
for (FileHandle fileHandle:allList)
System.out.println(fileHandle);
Output on IDE Run tab :
true true list/enemy/1.png list/enemy/2.png list/enemy/3.png
There is no any output on IDE local Terminal. My IDE is Intellij IDEA, hopefully result should be same on other IDE.
That is my expected output.
FileHandle's readString() reads the entire file into a string using the platform's default charset and if file handle represents a directory, doesn't exist, or could not be read then throw GdxRuntimeException.
I make a project in netbeans including jasperreports and then I covert project to jar file. i want when i run the jar file of project the jasperReports file also work fine....... but for this I used the following code
the exception is come... from code...
I try the following code
//code
InputStream input = this.getClass().getResourceAsStream("Users/Kashif/Desktop/Muhammad Kashif/Documents/NetBeansProjects/Torch/Reports/report11.jrxml");
JasperDesign jd = JRXmlLoader.load(input);
Map map = new HashMap();
map.put("Discount", para);
map.put("Customer", para1);
map.put("Total", para2);
JasperReport jasperReport = JasperCompileManager.compileReport(jd);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, con);
//view report to UI
JasperViewer.viewReport(jasperPrint, false);
//error
net.sf.jasperreports.engine.JRException: java.net.MalformedURLException
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:305)
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:284)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:273)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:247)
at torch.UserGui.printBtnActionPerformed(UserGui.java:1269)
.....
.....
.....
Caused by: java.net.MalformedURLException
at java.net.URL.<init>(URL.java:619)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.commons.digester.Digester.parse(Digester.java:1892)
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:297)
... 42 more
Caused by: java.lang.NullPointerException
at java.net.URL.<init>(URL.java:524)
... 53 more
The exception might come because of a missing jrxml file.
You have to make sure that wherever you deploy your JAR file (not clearly understandable) this relative path and file (no preceding slash!) exists:
Users/Kashif/Desktop/Muhammad Kashif/Documents/NetBeansProjects/Torch/Reports/report11.jrxml
For example, if you deploy on a Linux server in your home path, you have to make sure there is a file in
/home/username/Users/Kashif/Desktop/Muhammad Kashif/Documents/NetBeansProjects/Torch/Reports/report11.jrxml
On Windows, you have to make sure that the file is lying underneath your directory structure, e.g.
C:\mypath\java -jar xyz.jar
C:\mypath\java\Users/Kashif/Desktop/Muhammad Kashif/Documents/NetBeansProjects/Torch/Reports/report11.jrxml
I'm making a simple game.
Eclipse reads a text file but when I export my project as runnable jar file it doesn't read it.
My resource folder looks like this: http://i.stack.imgur.com/LK2SF.png
The code:
BufferedReader br = new BufferedReader(
new FileReader("Resources/LevelManager/LevelManager.txt"));
When i run runnable jar file I get this error:
java.io.FileNotFoundException: Resources\LevelManager\LevelManager.txt (System cant find the path)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at LevelManager.Utils.getLevel(Utils.java:13)
at LevelManager.LevelManager.<init>(LevelManager.java:15)
at State.GameState.<init>(GameState.java:26)
at Main.Game.init(Game.java:54)
at Main.Game.run(Game.java:80)
at java.lang.Thread.run(Unknown Source)`
Thank you for your answers.
This is a classical error.
Your application will run in its own jar; which means its resources will be included in the jar and not available as File objects. You need to use a classloader.
I'm not sure how you intend to read from the resource but here is how to obtain a stream from a resource (and please note that slashes are used for separators, always:
#WillNotClose //this is a JSR 305 annotation
public static InputStream loadResource(final String resourcePath)
throws IOException
{
final URL url = EnclosingClass.class.getResource(resourcePath);
if (url == null)
throw new IOException(resourcePath + ": resource not found");
return url.openStream();
}
I am trying to lay down some core files in a dev-test-prod setup. Basically if the file is newer it needs to be copied to the next level as part of the QA process.
I am using Java 8 so I decided to try the NIO Files/Path apis for the first time. I am creaky old, having been programming for 48 years and have used almost exclusively Java since early 1996, and every release since prerelease, so this NIO "enhancement" should not be too hard for me to assimilate, but . . .
FileSystem fs = FileSystems.getDefault();
Path in = fs.getPath(fromFileName);
Path out = fs.getPath(toFileName);
if (Files.exists(out)) {
FileTime inTime = Files.getLastModifiedTime(in);
FileTime outTime = Files.getLastModifiedTime(out);
if (0 > outTime.compareTo(inTime)) {
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
}
} else {
Files.createFile(out);
Files.copy(in, out);
}
I initially just tried Files.copy() without Files.createFile() and got a NoSuchFileException on the copy() call.
I looked a several StackOverflow posts which referred to this, one of which stated authoritatively that copy() will fail if the destination file does not already exist. For the life of me I cannot understand why the designers thought this was a good idea, but so be it. I accordingly added the createFile() call as above (having read the API doc for Files which says that Files.createFile() "Creates a new and empty file, failing if the file already exists." When I ran it again I got exactly the same Exception, but on the createFile() instead of the copy(). Notice the path is inside my home directory on Windows, so no access denied issues should occur. Also NOTHING other than Eclipse containing this project is running on my PC at this time.
java.nio.file.NoSuchFileException: C:\Users\ChrisGage\myproject\site\ttws\css\core.css
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.createFile(Unknown Source)
...
What am I doing wrong?
Files.copy() (and Files.move() for that matter) is "dumb"; it won't try and do any of the following:
copy entire directory hierarchies;
move entire directory hierarchies (if the source and target are on different filesystems);
create missing directories etc.
You need to do:
final Path tmp = out.getParent();
if (tmp != null) // null will be returned if the path has no parent
Files.createDirectories(tmp);
prior to copying the file.