FileOutputStream not writing to files - java

I have written this program trying to write to a text file,but nothing is happening after executing the program.Can you suggest how to specify filepath? I am using eclipse and have created a file "out.txt" in the same default package where my class is.
import java.io.*;
public class InputOutput {
public static void main(String args[]) throws IOException
{
int i;
//File file=new File("inputd");
//File file0=new File("out");
FileInputStream fin=null;
//FileOutputStream fout=null;
DataOutputStream fout=null;
//copy the file
try
{
//fin=new FileInputStream("input.txt");
fout=new DataOutputStream(new FileOutputStream("out.txt"));
//fout=new FileOutputStream("out.txt");
fout.write(1);
fout.write(100);
fout.write(1000);
}
catch(IOException ioe)
{
System.out.println("I/O Error" + ioe);
}
finally {
if (fout != null) {
fout.close();
}
//fin.close();
}
}
}

The file will be automatically created and will be in your projects root folder.
Also, if you don't see the file in your project in Eclipse, click on your project in the project explorer and press F5 or right click on your project and select refresh.

Related

Java doesn't find solution package in resource folder Intellij

This sample is supposed to locate the copied over .zip file from the build output directory but for some reason it doesn't find that file. I created a resource directory in the root directory and marked it as "Resource Root" and still didn't work. Any help is appreciated. Here is a snippet of the code:
if (install && package == null) {
File file = new File("file.zip");
byte[] bytes = new byte[(int) file.length()];
try {
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
}
catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
return;
}
catch (IOException ex) {
System.out.println("Error Reading The File.");
ex.printStackTrace();
}
Here is a screenshot of the project structure:
Project Structure
I suppose you mean you've created the file in the /main/resources folder of your project?
If that's so, then you can copy it as such:
public static void main(String[] args) throws IOException {
var path = Main.class.getResourceAsStream("/myfile.txt");
Files.copy(path, Path.of("file.txt"));
}

pdf file does not open from the jar ubuntu 16.04

I am using the following code to open a pdf file from java. The code works when I run the application from the IDE. However, when generating the jar and executing it, the code stops working. I do not know what I'm doing wrong. I have tried changing the jar of folders but it still does not work. It seems that the problem is how ubuntu 16.04 handles the routes because in windows this works correctly. The application does not throw exceptions
The way I get the pdf I do the same for another application but in it I get an image and it works both in the jar and in executing it in the ide.
jbTree.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tree.png")));
Button code
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File (getClass().getResource("/help/help.pdf").toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException | URISyntaxException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
The solution is run the application through the console. Trying to run it in another way does not work.
When you run the project from your IDE then the root of your project is the System.getProperty("user.dir") e.g if it Your project root folder is PDFJar the it will look for the help.pdf in the PDFJar/src/project/help/ folder.
After building your project to jar file the executable jar is build and executed from a dist or bin folder which is now the System.getProperty("user.dir") and the help.pdf will be seeked in the dist/src/project/help/ folder.
You either create the folder /src/project/help/ with help.pdf in it in your dist or bin directory or put your Jar file in your project root
EDITED
You can't access a resources file packed into your JAR archive as file except as input stream, The reason it works from you IDE is because the file exist in the src folder as the executed directory is your project folder. You will need to create the file outside the JAR achive then read the stream into it so you can call Desktop to open it.
package stackoverflow;
import java.awt.Desktop;
import java.awt.HeadlessException;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author thecarisma
*/
public class StackOverflow {
public void openHelpFile() {
OutputStream outputStream = null;
try {
File outFile = new File("./help.pdf");
outFile.createNewFile(); //create the file with zero byte in same folder as your jar file or a folder that exists
InputStream in = getClass().getResourceAsStream("/help/help.pdf");
outputStream = new FileOutputStream(outFile);
int read = 0;
//now we write the stream into our created help file
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
if (outFile.exists()) {
String path= outFile.getAbsolutePath();
JOptionPane.showMessageDialog(null, path);
if (Desktop.isDesktopSupported()) {
JOptionPane.showMessageDialog(null, "Enter");
try {
File myFile = new File (path);
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Exception");
}
}
} else {
JOptionPane.showMessageDialog(null, "Error Occur while reading file");
}
} catch (HeadlessException | IOException ex) {
Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
StackOverflow stackOverFlow = new StackOverflow();
stackOverFlow.openHelpFile();
//the bellow example works for file outside the JAR archive
/**
String path= new File("help.pdf").getAbsolutePath();
JOptionPane.showMessageDialog(null, path);
if (Desktop.isDesktopSupported()) {
JOptionPane.showMessageDialog(null, "Enter");
try {
File myFile = new File (path);
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Exception");
}
} **/
}
}
DETAIL
When your resources file is packed into the JAR archive it cannot be accessed as a file except as a stream of file. The location of the file will be absolute in the JAR archive such as the /help/help.file.
If you just want read the content of the resources such as conf, xml, text file or such you can just read it into BufferReader i.e
InputStream in = getClass().getResourceAsStream("/conf/conf.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
else if it a binary file you will need to create a file outside the jar file with 0 byte then read the resources stream from the JAR archive into the created file.
NOTE: You should check if the help file already exist with the same size before reading from the JAR archive to prevent reading multiple time and skip the process to increase you run time. Take note while creating your file as creating a file in a folder that does not exist in JAVA is not possible.
YOU CAN OPEN YOUR .jar FILE WITH AN ARCHIVE MANAGER, TO VIEW IT STRUCTURE

I am trying to run file program, I get error FileNotFoundException

import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
I try create file to read and write from where the code will be stored. In my case it was stored in C drive (my program thats I created it there only read and write file).
My program builds successfully but no output
application name - javaprogram
package name- pack
Inside package I have placed two files c.txt and m.txt
I even want to know how is that we have .java file (I was trying with c.txt and m.txt rather than .java)
This IS WHAT I GET ERROR
init:
deps-jar:
Compiling 1 source file to C:\Users\user\Documents\NetBeansProjects\JavaApplication1\build\classes
compile-single:
run-single:
Exception in thread "main" java.io.FileNotFoundException: file (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at javaapplication1.C.main(C.java:20)
Use the code below you are missing something file object
class C {
public static void main(String args[])
{
try
{
File f1 = new File("C.java");
File f2 = new File("M.java");
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read()) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Another elegant way of doing that is
download Commons IO from this Link and add it to your project library then use the code below.
class C {
public static void main(String args[]) throws Exception
{
try
{
File f1 = new File("C.java");
File f2 = new File("M.java");
FileUtils.copyFile(f1, f2);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
} }

Where do i have to put input file in eclipse(java) in order to write into it

I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank.
Here is my code
package com.example.ex2;
import java.io.*;
class Input{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("abc.txt");
String s="Good MOrning";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);}
}
}
I think i have gone wrong in placing the text file. I have placed it in the default directory.
Your code works fine. Check the correct file.
If you are running from IDE, it will be in the current working directory.
It is always better to your a temp or directory to store files ( certainly not in working dir)
Here is a best practice code. You can tune it further if you wish
public static void main(String args[])
{
FileOutputStream fout = null;
try
{
File f = new File("abc.txt");
if (!f.isFile())
f.createNewFile();
fout = new FileOutputStream(f);
String s = "Good MOrning";
byte b[] = s.getBytes();
fout.write(b);
System.out.println("success... printed at : " + f.getAbsolutePath());
} catch (Exception e)
{
System.out.println(e);
} finally
{
if (null != fout)
try
{
fout.close();
} catch (IOException e)
{
}
}
}

Can't delete the file after writing some data to it, where is wrong?

I'm write some text a file then delete it, but the deletion is failed.
The code is very simple:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestFile {
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
public static void writeFile(File file, String content) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
}
}
The output is:
Deleted? false
And there is a file abc.txt contains hello still there under c:.
Then I use FileUtils.writeStringToFile(...) from commons-io.jar instead, the file will be deleted.
But I don't know where is wrong with my code, please help me to find it out.
You are only closing the file if you get an IOException.
Change it to a finally block and you will be able to close and delete the file.
public static void writeFile(File file, String content) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(content.getBytes("UTF-8"));
} finally {
try {
out.close();
} catch (IOException ignored) {
}
}
}
You need to close your OutputStream when you finished writing the file.
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
out.close();
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
In your main method,
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
You open the file, write to it and then do not close it. Java keeps the file open for you, so if you wanted to add more information to it, you could. However, to be able to delete the file, you need to make sure no other reference is open to it. You can do this by using file.close() to close the file handle Java reserves for you.
It's best practice to always close a stream when you are done with it, especially if you added data to it. Otherwise, you might run into situations where you are keepings files open by accident, or, in extreme cases, lose data you thought was saved already.
Have a look at what FileUtils.writeStringToFile() does that you haven't.
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = new java.io.FileOutputStream(file);
try {
out.write(data.getBytes(encoding));
} finally {
IOUtils.closeQuietly(out);
}
}
You will note that the out stream is always closed, wheras in your example it only gets closed in your catch block if the write() throws an exception.
On Windows, files that are open by any program cannot be deleted.
You just delete your file if an exception occurs. You need to do that every time, after you opened the file.
You may want to put close into a finally block.
If you're using Java 7 I consider using a try-with-ressources block, which takes care of closing files for you.
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}

Categories