Terminal input gives null pointer but IDE input runs fine - java

Trying to build a program that changes stuff in SRC folder. for (File f : files) { Returns a null pointer despite returning appropriate answer in Intellij IDE. This program searches my SRC file directory and lists all files pertaining to the the directory. It works fine in the IDE but does not do the correct function on the command line.
//This program is from Liang Comprehensive Java 12.18
import java.io.*;
import java.util.ArrayList;
public class AddStatement {
public static void main(String[] args) throws IOException {
// File dir = new File(args[0]);
File dir=new File("src");
System.out.println(dir.getCanonicalPath() + " Was put into console");
writeTofile(getfiles(dir));
}//End of main class
public static ArrayList<String> getfiles(File dirc) throws IOException {
ArrayList<String> paths = new ArrayList<String>(5);
File[] files = dirc.listFiles();
for (File f : files) { //This part is where null is happening
paths.add(f.getCanonicalPath());
}//End of foreach
return paths;
}//End of getFiles method
public static void writeTofile(ArrayList<String> files) throws IOException {
String file;
int count = 1;
for (String f : files) {
file = f;
try (PrintWriter writer = new PrintWriter(new FileWriter(file, true))) {
if (file.contains("Chapter")) {
writer.print("\\\\Chapter" + count);
count++;
}//End of filtering if
}//End of try block
}//End of for loop
System.out.println("Files written");
}//End writeTofile
}// End of Class

Related

Console doesn't display result

I'm writing some code to get the latest file from a directory but the console doesn't display any result.
Here's the code I've written :
import java.io.File;
public class test {
public static File getLastModified(String directoryFilePath)
{
File directory = new File("C:\\New folder");
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
System.out.println(file);
}
}
}
return chosenFile;
}
public static void main(String[] args) {}
}
You have to do 2 things,.
Need to call getLastModified() method in your main method
Scanner reading each line in the file and doing system. print calls? while (scanner.hasNextLine()) { System.out.println(blah blah blah); }
Simple. Done!

Recursion method to display the directory structure of a path (Java)

Our teacher gave us question to Write a recursive method to display the directory structure of a path.
He want the output to look like this :
testdir
+--f1
+--d2
+--d22
+f221
+f212
+f211
+--f2
+--d1
+--f12
I used this method :
package Task;
import java.io.File;
import java.io.IOException;
public class Recursive {
public static void main(String[] args) {
File currentDirectory = new File(" . "); // current directory
displayDirectoryContents(currentDirectory);
}
public static void displayDirectoryContents(File dirct) {
File[] myfiles = dirct.listFiles();
for (File file : myfiles) {
if (file.isDirectory()) {
//it worked when i used file.getCanonicalPath()); but file.getName()); does not work
System.out.println("directory : " + file.getName());
displayDirectoryContents(file);
}
else {
//it worked when i used file.getCanonicalPath()); but file.getName()); does not work
System.out.println(" files : " + file.getName());
}
}
}
}
The getName does not work and give me an erorr (
Exception in thread "main" java.lang.NullPointerException
at lab16.displayDirectoryContents(lab16.java:17)
at lab16.main(lab16.java:10)
)
i've rewritten algorithm and it works with .getName() without any problem. I didn't do any indentations tho.
import java.io.File;
public class Recursive {
private static void TraverseDirectory(File[] files) {
if (files.length == 0) return;
for (File file : files) {
if (file.isFile()) System.out.println(file.getName());
else {
// is DIR
System.out.println(file.getName());
TraverseDirectory(file.listFiles());
}
}
}
public static void main(String[] args) {
File cur_dir = new File("/");
TraverseDirectory(cur_dir.listFiles());
}
}
EDIT: after you edited your question, I can now see what was the problem. You weren't returning anything when the content of the directory was empty (it was null). Therefore, it couldn't traverse null value.

How to concatenate files from an array to into a new folder? [duplicate]

This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 6 years ago.
I am trying to write a java program that will take two arguments, dirName and fileName. The program will search for all the files in dirName that end with .java and then concatenate them into a new folder called fileName. So far I have a method to search for .java files in dirName, I then put them in a file array called list but now I am struggling to iteratively add the files in this array to my new folder, fileName. Here is what I have so far:
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class TwoFiles {
File dir;
File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public File[] Finder(File dir) {
dir = getDir();
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return name.endsWith(".java"); }
} );
}
public static void main(String[] args) {
File folder = null;
File newFolder = null;
Integer b = null;
TwoFiles tf = new TwoFiles(folder, newFolder);
folder = tf.getDir();
newFolder = tf.getNewFolder();
File[] list = tf.Finder(folder); //add to an array
//here is where I've been experimenting to add files in `list` to new folder, `fileName`.
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
newFolder.write(b);
inFile.close();
}
//copy files from array (list) into newFolder
}
}
Thanks for your time.
Your newFolder variable is of type File. You cannot write into this. I assume, your code does not even compile. You have to create an output stream in front of your loop:
FileOutputStream fos = new FileOutputStream( newFolder);
try
{
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
fos.write(b);
inFile.close();
}
}
finally
{
fos.close();
}
You can use the Apache Commons IO copyDirectory() with the IOFileFilter (for .java extensions) to copy your files from one directory to another. Before that you can ensure to create a new directory using forceMkdir() for your filename.
It's my version of your problem:
I created other constructor, where you can put only paths to directory/folder from you want concatenate files, and to file of concatenations result.
public class TwoFiles {
private File dir;
private File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public TwoFiles(String dirName, String destinationFileName) throws IOException{
dir=new File(dirName);
if(!dir.isDirectory()){
throw new FileNotFoundException();//here your exception in case when dirName is file name instead folder name
}
name=new File(destinationFileName);
if(!name.exists()){
name.createNewFile();
}
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public void concatenateFiles() throws IOException{
File[] files=dir.listFiles();
for(File file: files){
if(file.getName().endsWith(".java")){ //check is right file
prescribe(name, file);
}
}
}
/** prescribe file to new destination */
private void prescribe(File destination, File file) throws IOException {
FileInputStream inFile = new FileInputStream(file);
FileOutputStream writer=new FileOutputStream(destination, true); //true means next file will be write beginning from end of the file
int x;
while((x=inFile.read())!=-1){
writer.write(x);
}
String test="\n"; //next line in file
writer.write(test.getBytes());
writer.close();
inFile.close();
}
public static void main(String...strings){
String dirName="C/myApp/model/entity";
String fileName="C:/Users/Dell/Desktop/temp/test.java";
try {
new TwoFiles(dirName, fileName).concatenateFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

how to read the data from the files of a directory

public class FIlesInAFolder {
private static BufferedReader br;
public static void main(String[] args) throws IOException {
File folder = new File("C:/filesexamplefolder");
FileReader fr = null;
if (folder.isDirectory()) {
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
try {
fr = new FileReader(folder.getAbsolutePath() + "\\" + fileEntry.getName());
br = new BufferedReader(fr);
System.out.println(""+br.readLine());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
br.close();
fr.close();
}
}
}
}
}
}
how to print the first word from first file of a directory and the second word from second file and third word from a third file of the same directory.
i am able to open directory and print the line from each file of the directory,
but tell me how to print the first word from first file and second word from second file and so on . .
Something like the below will read first word from first file, second word from second file, ... nth word from nth file. You'll likely want to do some additional work to improve the codes stability.
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public class SOAnswer {
private static void printFirst(File file, int offset) throws FileNotFoundException, IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ( (line = br.readLine()) != null ) {
String[] split = line.split(" ");
if(split.length >= offset) {
String targetWord = split[offset];
}
// we do not care if files are read that do not match your requirements, or
// for reading complete files as you only care for the first word
break;
}
br.close();
fr.close();
}
public static void main(String[] args) throws Exception {
File folder = new File(args[0]);
if(folder.isDirectory()) {
int offset = 0;
for(File fileEntry : folder.listFiles()) {
if(fileEntry.isFile()) {
printFirst(fileEntry, offset++); // handle exceptions if you wish
}
}
}
}
}

Recursively file search not working

What i wanna do is to recursively search for some files on the external sd-card. The problem is that the code is looking ok, but (assuming .txt files) it only shows me 7 files out of 100+ that are being spread throughout folders.
The code is this:
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
void makelist(File file){
if(file.isFile()){
if(SimpleAdapter.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
Any idea how could i make it run correctly?
Assuming you are building two lists (misc files and doc files), try with below code which all all files other than text files to misc and text files to doc.
if(SimpleAdapter.getFileType(file) == null || !SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
mis.add(file);
else
doc.add(file);
Not sure why it is not working for you. Tried a test program and it worked perfectly...
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileChecker
{
/**
* #param args
*/
public static void main(String[] args) {
SimpleAdapterTest adapter = new SimpleAdapterTest();
adapter.makelist(new File("C:\\MYFolder"));
adapter.showList();
}
}
class SimpleAdapterTest
{
List<File> mis = new ArrayList<File>();
List<File> doc = new ArrayList<File>();
public static String getFileType(File f)
{
String Name = f.getName();
if (f.getName().endsWith(".txt") || Name.endsWith(".TXT")
|| Name.endsWith(".inf") || Name.endsWith(".INF"))
return "text";
return null;
}
public void makelist(File file){
if(file.isFile()){
if(SimpleAdapterTest.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapterTest.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
public void showList()
{
for(File miscFile : mis)
{
System.out.println("Misc files = " + miscFile.getName());
}
for(File docfile : doc)
{
System.out.println("Doc files = " + docfile.getName());
}
}
}

Categories