Java Error: NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm totally new in this world. I want to make a simple file move program. It works fine with only 1 file and until I add the new code for multiple files move. But I wanted more and I added multiple file selection to JFileChooser. To do the move of files I search around the web and found some users that asked for something similar to it. I tried to put it in my code but I've obtained an Error like this:
Exception in thread "main" java.lang.NullPointerException
at jfile.main(jfile.java:27)
Line 27 is: for (int i = 0; i < files.length; i++) {
This is the code, thanks you and sorry for my bad English.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.swing.JFileChooser;
import org.apache.commons.io.FileUtils;
public class jfile {
public static void main (String[] args) throws IOException{
System.out.println("Creado por: MarcosCT7");
if (new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods").exists());{
System.out.println("Seleccione el mod a instalar:");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);
int returnVal = chooser.showOpenDialog(chooser);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("Se está instalando " + chooser.getSelectedFile().getName());
File fuente = new File(chooser.getSelectedFile().getAbsolutePath());
File destino = new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods");
File[] files = fuente.listFiles(); //thats new added
for (int i = 0; i < files.length; i++) {
File destFile = new File(destino.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "")); //until here its new added
FileUtils.moveFileToDirectory(files[i], destFile, true); //changed to multiple move, before it was: FileUtils.moveFileToDirectory(fuente, destino, true);
}
}
else {
if(returnVal == JFileChooser.CANCEL_OPTION) {
System.out.println("No se ha seleccionado ningun mod. Adios.");
}
}
}
}
}

NullPointerException means that the variable doesn't hold any reference to a object. What I mean by reference is, For ex:
String path="";
File f=new File(path);
if(f.exists()) {
// do something
}
f is a variable of type File which holds a reference to a object File defined by path
and now you can use variable f just like any other variable call methods on that variable etc.
Another example
File f;
if(f.exists()) {
// do something
}
Now you will get NullPointerException in line if(f.exists()) because f doesn't hold any reference.
In JAVA new keyword is used to assign new reference. JVM will take care of all the low level details. It is similar to pointers in c and c++. In JAVA you don't have to explicitly delete the objects. JVM garbage collector will take care of these things. Java is object oriented language
Do read and understand OOP comcepts

Before you iterate through files using the loop, check using an if statement:
if(files==null){
System.out.println("Files not found");
}
else{
for (int i = 0; i < files.length; i++) {
File destFile = new File(destino.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "")); //until here its new added
FileUtils.moveFileToDirectory(files[i], destFile, true); //changed to multiple move, before it was: FileUtils.moveFileToDirectory(fuente, destino, true);
}
}

Related

Reading and Printing All Directories and Files in Java With Only Loops [duplicate]

This question already has answers here:
Traversing directories without using recursion?
(8 answers)
Closed 2 years ago.
I am trying to read all the directory and files including the subdirectories. Each time it finds the files and directories, the program will print what's inside the folder. This will continue if it finds another directory and prints its contents as well. I'm having trouble getting the other directory data when there are multiple folders in a directory. My code only works when there is only one way to go. Here is my code. DirFolder3 should print its contents as well. This program shouldn't use recursion as well. The output should be like the DirFolder1, DirFolder2, and DirFolder4 directories. Thanks for your help.
Main File:
import java.io.IOException;
public class DirectoryRead {
public static void main(String[] args) throws IOException {
DirInfo scan = new DirInfo();
scan.readDirectory();
}
}
Read Class:
import java.io.File;
import java.io.IOException;
public class DirInfo {
String dirName = "";
String childName = "";
String fileName = "";
public void readDirectory() throws IOException {
//starting directory
File dir = new File("C:\\DirFolder1");
//if a directory (parent) exists, loop
while (dir.exists()) {
//print the parent/current directory name
dirName = dir.getName();
System.out.println(dirName);
//list all files in current directory
File [] files = dir.listFiles();
//loop through array and see if a directory or file exists
for (int i = 0; i < files.length; i++) {
//if there's a directory, print name
if (files[i].isDirectory()) {
childName = files[i].getName();
System.out.println("\t" + childName);
}
//if there's a file, print name
if (files[i].isFile()) {
fileName = files[i].getName();
System.out.println("\t" + fileName);
}
}
//make child directory the new parent/current directory and repeat
dir = new File(dir, childName);
}
}
}
Output:
DirFolder1
DirFolder2
Sample File1.txt
DirFolder2
DirFolder3
DirFolder4
Document2.txt
Document3.txt
DirFolder4
Dir4TextFile.txt
You are looking for traversing the directory with BFS. It is alternative to DFS which is using recursion.
With BFS you can use Queue or another data structure to keep track of the sub directories that you haven't traversed yet. Depends on what output you want to have (which order to traverse) you can decide in which order you are pasting and retrieving the elements from this DS.
You can check the implementation here https://www.techiedelight.com/traverse-given-directory-bfs-dfs-java/

Creating files with names from ArrayList [duplicate]

This question already has an answer here:
Java not creating file
(1 answer)
Closed 4 years ago.
I am looking for a way to make a bunch of empty txt files that would be named after elements of an ArrayList in Java.
Assuming that fList has "Apple", "Banana" and "Cherry", this piece of code should create Apple.txt, Banana.txt and Cherry.txt in the project directory.
Unfortunately, it does not, and I do not understand why. I assume it's a logic or syntax error.
public void ViewList() {
for (String fruits : fList) {
String fileName = fruits;
File f = new File(appDir + fileName + ".txt");
if (f.exists() && f.isFile()) {
System.out.println("Success!");
}
}
Can you help me understand what's wrong?
Everything is correct in your code except few lines.
for (String fruit : fList) {
//String fileName = fruits;
File file = new File(appDir + fruit + ".txt");
//OR if appDir doesn't end with `/` or `\` use
//File file = new File(appDir, fruit + ".txt");
// Create the file
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
}
Also You can refer this link for more info:
https://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/
Note: Please note it down, file path strategy will vary between windows and unix system. So create filepath according to that.

Java file.exists() Errors

I am currently working on a "Notepad - type" file for my Object-Oriented Java class. I've got most of the program done - however I am stuck on the following issue:
When the program tries to save a file, it is supposed to first check for a files existence, obviously if the file exists the program will prompt the user for permission to overwrite the existing copy of the file [The overwrite prompt is not written yet, but it will go in the if(selectedFile.exists() == true) portion of code] - and if the file does not exist, the program will create it.
The issue I am having is that the program always creates the file before checking for the files existence. I have looked at probably 20-30+ answers to similar questions - mainly on stackoverflow, and have yet to come across the answer i need. I'm not sure if I am just "not getting it", or if I have really done something wrong..
Any answer - or hint as to where to find the answer - to this issue would be greatly appreciated.
Thank You.
Complete code (for the save portion of the program is shown below).
else if(source == saveFile)//-------------------------//SAVE FILE//--------------------------
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setDialogTitle("JavaPad - Save File");
int result = fileChooser.showSaveDialog(fileChooser);
String myFile;
try
{
if(result == JFileChooser.APPROVE_OPTION)
{
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
String[] lines = textArea.getText().split(System.getProperty("line.separator"));
readToSave = new Scanner(lines.toString()); // CANNOT use toString() on an Array - THIS WILL BE CHANGED PROPERLY?
PrintWriter savePWriter = new PrintWriter(selectedFile);
if(selectedFile.exists() == true)
{
JOptionPane.showMessageDialog(null, "This file already exists.");
statusLabel.setText("File Save Aborted...");
}
else
{
System.out.println("Creating File: " + myFile);
File newFile = new File(fileChooser.getSelectedFile().getName());
savePWriter = new PrintWriter(newFile);
int i = 0;
while(i < lines.length)
{
savePWriter.append(lines[i] + "\n");
System.out.println("Lines appended = " + i);
i++;
}
savePWriter.flush();
savePWriter.close();
statusLabel.setText("File Saved.");
}
}
else
{
JOptionPane.showMessageDialog(null, "Save has been canceled.");
}
}
catch(IOException IOSaveError)
{
System.out.println(IOSaveError);
}
}
You are calling new PrintWriter(selectedFile), which creates the file, right before you check whether selectedFile exists.
Don't create the PrintWriter before checking if the file exists. The PrintWriter is what causes the file to be written to.
You do:
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
PrintWriter savePWriter = new PrintWriter(selectedFile); // Creates File! Probably unwanted.
if(selectedFile.exists() == true) // always true because of the line above
By the way, your code is far too complicated. Instead of having the variables selectedFile and newFile, which both are newly created File objects, you could simply use the File object returned by the dialog: newFile = fileChooser.getSelectedFile().
if(selectedFile.exists() == true)
can be simplified to
if (selectedFile.exists())
I recommend to do I/O using try-with-resources whenever possible:
try (final PrintWriter writer = new PrintWriter(selectedFile)) {
// Use writer
}
This helps with accidentally forgetting to close streams.

Incompatible types Required: File, Found:void

I'm trying to programatically set the ID3 tags of some mp3s. After having gave up the jaudiotagger I found the MyID3 library http://www.fightingquaker.com/myid3/
I'm by no means an experienced Java programmer, but I have some knowledge of OOP.
I managed to get as far as writing a class, everything works well, except for a strange error, that I can't understand.
My class is:
import org.cmc.music.myid3.*;
import org.cmc.music.metadata.*;
import java.io.*;
import java.lang.*;
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class lrsetid3 {
public static void main(String[] args) {
String files;
File inputfolder = new File("c:\\ID3\\input");
File[] listOfFiles = inputfolder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
// files = listOfFiles[i].getName();
}
try {
MusicMetadataSet src_set = new MyID3().read(listOfFiles[i]);
IMusicMetadata metadata = src_set.getSimplified();
String artist = metadata.getArtist();
metadata.setArtist("Bob Marley");
System.out.println(listOfFiles[i].getName());
File src = new File ("c:\\ID3\\input" + listOfFiles[i].getName());
System.out.println(listOfFiles[i].isFile());
System.out.println(listOfFiles[i].exists());
File dst = new MyID3().write(src, dst, src_set, metadata);
// System.out.println("Artist" + artist); // Display the string.
}
catch (Exception e){
e.printStackTrace();
}
}
}
And the error that I get is on the line:
File dst = new MyID3().write(src, dst, src_set, metadata);
lrsetid3.java:37: error: incompatible types
File dst = new MyID3().write(src, dst, src_set, metadata);
^
required: File
found: void
1 error
The weird part is that the printouts say that the first parameter of the write function is a File... I do not get why the compiler does not want to accept src as a File variable.
Many thanks for your help
that will return a new MyID3 object.
File dst = new MyID3();
This however, will return what the write() method returns. In this case void. (I presume)
File dst = new MyID3().write(src, dst, src_set, metadata);
To fix it, do this:
File dst = new MyID3();
dst.write(src, dst, src_set, metadata);
And of course, the same rule applies to this line:
MusicMetadataSet src_set = new MyID3().read(listOfFiles[i]);

How can I write consecutive named files in Java?

I have a method for saving a File, but I don't know how to save files with consecutive names such as file001.txt, file002.txt, file003.txt, filennn.text
How can I achieve this?
You can use the following line of code to create the filenames.
String filename = String.format("file%03d.txt", fileNumber);
Then you will just use that string to create new files:
File file = new File(filename);
The following code will create files numbered 1 - 100:
for (int fileNumber = 1; fileNumber <= 100; fileNumber++) {
String filename = String.format("file%03d.txt", fileNumber);
File file = new File(filename);
}
Or, you will need to have a static variable that you increment every time you create a new file.
private static int fileNumber = 0;
public void createNewFile(){
String filename = String.format("file%03d.txt", fileNumber++);
File file = new File(filename);
}
It may be desirable for you to skip over writing to a file if it already exists.
This could be done easily by placing the following at the beginning of the for loop proposed by Justin 'jjnguy' Nelson, for example:
if(new File(fileName).exists())
{
continue;
}

Categories

Resources