IOException : When Executing Java File Code in Linux box - java

Here is My WriteFile
WriteFile.writeFile(str, "./test/my.html");
And writeFile() method code
public static void writeFile(String content, String fileName)
{
try
{
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This Code Working fine With Windows but in Linux I am getting below exception
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at org.sewa.util.WriteFile.writeFile(WriteFile.java:25)

Behavior of createNewFile is the same in Windows and Linux, so most likely the path of the file you're specifing exists in Windows while it does not in Linux. In your example, test/ directory does not exist in Linux in the directory where you're executing the program. If you want to create the whole path, see File#mkdirs.

Related

How do I write to a File stored in a path in Java

I have a Path variable like this:
Path output;
This path is initialized in the main-method.
I want to check if there exists a File in this path
and if thats the case- write a string into that file.
Else create a new File with the given path and write
the string.
//void parseOutput(String s){
//if (file in path exists)
// write(s in file from path)
else
File f = new File(String.valueOf(output));
write String in f
You can try this :
import java.io.*;
class FileDemo {
public static void main(String str[]) {
String path = "E:/myfile.txt";
File file = new File(path);
if(file.exists()) {
System.out.println("File is exist..!!!");
} else {
try {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write("This is my first file..!!");
fileWriter.close();
System.out.println("File has some content..!!");
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
If you have a Path, it doesn't really make sense to convert that to a String and use the File constructor.
For checking if a file exists, you can use Files exists.
To add to an existing file, have a look at Files.newBufferedWriter with the APPEND OpenOption set.
Full example:
Path path = Paths.get("/path/to/file.txt");
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufferedWriter))
{
printWriter.println("This is a line");
}
You might want to use exists() method in File class. Here's an example which you could use:
public void writeOnFile(String path, String str) throws FileNotFoundException {
PrintWriter out;
File file = new File(path);
if (file.exists()){
out = new PrintWriter(file.getPath());
out.println(str);
}
}

File not being created programmatically

I have written a method for an Android application:
public void doMethod()throws IOException{
Log.d("STORAGE", Environment.getExternalStorageDirectory().toString());
File file = new File(context.getExternalFilesDir("NOTES")+"TEST.txt");
Log.d("FILE", file.createNewFile()+"");
FileOutputStream os = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("HELLO WORLD");
bw.close();
Log.d("WRITE", "DONE");
}
In spite of executing this code (calling this method from an activity), I cannot see the file TEST.txt in my phone's file manager when I open the NOTES directory.
The directory named NOTES is being created without a problem. Where is my TEST.txt file going to?

Java 7 retrieve and read local file using fileinput stream

How can i retrieve and read local file using fileinputstream using Java 7. Something like this but for a local file. With the new security settings, I cant get it to work
public static InputStream openReading(String file)
throws FileNotFoundException
{
try
{
PersistenceService pService = (PersistenceService) ServiceManager
.lookup(PersistenceService.class.getCanonicalName());
URL fileurl = new URL(getCode() + file);
FileContents fc= pService.get(fileurl);
fc.setMaxLength(10240000);
InputStream in= fc.getInputStream();
return stream;
}
catch (MalformedURLException m)
{
m.printStackTrace();
}
catch (FileNotFoundException f)
{
throw new FileNotFoundException(f.getMessage());
}
}
ExtendedService.openFile is the equivalent for opening a file. That gives read/write access. There is no option to ask for read-only!

BufferedReader file not found

This is my code snippet:
static String filepath = "test.txt";
public static void main(String[] args) throws IOException {
try{
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String l = reader.readLine();
System.out.println(l);
}catch (FileNotFoundException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}
java.io.FileNotFoundException: test.txt (No such file or directory)
This is the exception I am getting.
What file path should I use? I put the text file in the bin folder.
I am running Eclipse on Ubuntu, it that matters.
If you are running eclipse and have a java project, then just put the file in the project and it will work.
Place the file at the root directory of the project folder. If your project root directory is FileReader, then place the file into it

How to create a file in a directory in java?

If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}

Categories