File not created in Java (Eclipse) - java

So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:
File file = new File("C://function.txt");
System.out.println(file.exists());
The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?

There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__ or
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}

After Java 7, you should use the new I/O API instead of the File class to create new files.
Here is an example:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}

You are just creating a File object, not a file itself. So in-order to create new file you need use below command:
file .createNewFile();
This would create your file under C:\ drive. Maybe you can also check if it is already exsits and handle exception etc.

If the file is not exist you can create a new file like:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}

The simplest way to do this:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());

try this:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();

Try this
File file = new File("C:/test.text");
f.createNewFile();

Related

Jar cannot find txt File in FileOutputStream

**I am trying to save and get Player objects from a Textfile and it works when using my IDE but when i create a Jar it can't find the text File. I tried with
this.getClas().getResources(path)
But still it didnt find the path to my text file.Can anybody Help?
public void setPlayer() throws FileNotFoundException {
ArrayList<Player> playerArrayList = new ArrayList<>();
playerArrayList = getPlayers();
Player player = new Player();
player.name = ViewManager.name;
player.score = Collision.points;
playerArrayList.add(player);
try{
FileOutputStream fileOut = new FileOutputStream("src/resources/highscore.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(Player player1 : playerArrayList){
out.writeObject(player1);
}
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
ยดยดยดยด
Resource files are not physical Files, as they can be inside a jar. They are intended to be read-only, and the class loader may cache them. They are case sensitive, with / as path separator and there path starts at the class path's root, probably src/resources.
So use the resource file as fall back resource to copy, if some physical file does not exist.
Path appDir = Paths.get(System.getProperty("user.home") + ".myapp");
Files.createDirectories(appDir);
Path file = appDir.resolve("highscore.txt");
if (!Files.exists(file)) {
// Copy resource to file, either:
URL url = getClass().getResource("/highscore.txt");
Path templatePath = Paths.get(url.toURI());
Files.copy(templatePath, file);
// Or
InputStream templateIn = getClass().getResourceAsStream("/highscore.txt");
Files.copy(templateIn, file);
}
try (FileOutputStream out = Files.newOutputStream(file)) {
...
}
Path is the generalisation of File.
I don't know what IDE you're using, but you're writing the file to the source sub directory. That directory might not be included in the jar.

Sub Directories under getCacheDir()

I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);

ThumbnailUtils.createVideoThumbnail

Can someone please tell me if what I'm doing is correct?
File directoryToStore;
directoryToStore = getBaseContext().getExternalFilesDir("MyFiles");
Bitmap b = ThumbnailUtils.createVideoThumbnail(directoryToStore + "/" + SavedVideoName, 3);
File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg"));
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying create a thumbnail from a video, but for some the FileOutputStream returns null.
I have checked the path of File newFile = new File(directoryToStore, SavedVideoName.replace(".mp4", ".jpg")); and it returns the correct path.
The video exists at the location I have given and I have permissions. I can't understand why it is gives me a null pointer?
According to this post, new FileOutputStream() will try to create a new file if it doesn't exist already. From the docs:
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
When you are debugging (at least in Android Studio), if you add a breakpoint and hover over newFile, it shows the file path. However, it doesn't show any details about the file, because the file doesn't (shouldn't) exist yet. You could try newFile.createNewFile() as suggested in the linked post, to confirm you are able to write the file first.

Android java. Create a folder and a file in the local DCIM folder

Is there any way to create a folder structure inside of the local DCIM folder of an Android phone?
Android 5.1
I need to create the next folder structure.
DCIM/Camera/Notes
and create a file there.
I do the next:
File internalDcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
internalDcimDir = new File(internalDcimDir, "Camera");
internalDcimDir = new File(internalDcimDir, "Notes");
internalDcimDir.mkDirs();
And when I try to create a file no exceptions occure
File file = new File(internalDcimDir, noteFileName);
And when I write something..
FileOutputStream outputStream = null;
try {
OutputStream fo = new FileOutputStream(file);
fo.write(content.getBytes());
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
it occures that there is no file and even dirs created.
May be I am doing something wrong. What can it be?

java how to check if file exists and open it?

how to check if file exists and open it?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
File.isFile will tell you that a file exists and is not a directory.
Note, that the file could be deleted between your check and your attempt to open it, and that method does not check that the current user has read permissions.
File f = new File("file");
if (f.isFile() && f.canRead()) {
try {
// Open the stream.
FileInputStream in = new FileInputStream(f);
// To read chars from it, use new InputStreamReader
// and specify the encoding.
try {
// Do something with in.
} finally {
in.close();
}
} catch (IOException ex) {
// Appropriate error handling here.
}
}
You need to create a File object first, then use its exists() method to check. That file object can then be passed into the FileInputStream constructor.
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}
You can find the exists method in the documentation:
File file = new File(yourPath);
if(file.exists())
FileInputStream file = new FileInputStream(file);

Categories