Problems printing a directory listing to the console - java

Sorry about readability. Stack appears to be trimming spaces from code lines & indents don't show up. Hrmph.
This was printing to the console without any problems...
CGT\whgdata\whnvp33.txt << EXPECTED OUTPUT (excerpt)
CGT\whgdata\whnvt30.txt
CGT\whgdata\whnvt31.txt
CGT\whgdata\whnvt32.txt
CGT\whgdata\whnvt33.txt
CGT\whgdef.txt
CGT\whgdhtml.txt
CGT\whibody.txt
etc....
...until I tried printing the hashtable to a file. Since that point, getFileListing isn't recognized as a valid symbol.
FileListing2.java:17: error: cannot find symbol
List<File> files = FileListing2.getFileListing(startingDirectory);
symbol: method getFileListing(File)
location: class FileListing2
1 error
Can someone lend a second set of eyes to help me uncover what I accidentally/overwrote. I'm sure it's something obvious. :\
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;
//
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
}

If your code is all you have for FileListing2, than there is no getFileListing() method for LileListing2, only a main() method

Yeah it IS something very obious, your class FileListing2 does not contain a method getFileListing(File). And it has to be static, the way you're trying to call it:
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
public static List<File> getFileListing(File f) {
/* implementation */
}
}

Related

In java BufferedReader doesn't find a file, even when file exists (and it's existance is confirmed using java)!

I am trying to use BufferedReader to read through the lines of a file, but it is giving me a FileNotFoundException. After some searching i found a way to check if a file exists (i used this : https://www.javabrahman.com/quick-tips/how-to-check-for-existence-of-a-file-in-java/). It returns true, so the file definitely does exist, and the path is right, however BufferedReader stil can't find it. I've looked at a bunch of possible solutions, but none seem to work.
Here is my code:
import java.io.*;
import java.lang.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class neki
{
public static void main(String[] args)
{
File file = new File("C:\\Users\\natan\\Desktop\\words.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String curr="AAAAAA";
int st=11184810;
String word;
boolean digit=false;
while(!curr.equals("ffffff"))
{
curr=Integer.toHexString(st);
for(int i=0;i<6;i++)
{
char c=curr.charAt(i);
if(Character.isDigit(c))
{
digit=true;
}
}
if(!digit)
{
for(int j=0;j<466545;j++)
{
word=br.readLine();
word=word.toLowerCase();
if(curr==word)
{
System.out.println(curr);
}
}
}
st++;
digit=false;
Path filePath_1= Paths.get("C:\\Users\\natan\\Desktop\\words.txt");
boolean fileExists_1= Files.exists(filePath_1);
System.out.println("File 'bleh' exists: "+fileExists_1);
}
}
}
These paths are not the same, one has 'test\' in the path, and the other doesn't.
new File("C:\\Users\\natan\\Desktop\\test\\words.txt");
Paths.get("C:\\Users\\natan\\Desktop\\words.txt");
Using a constant to hold static values referenced in multiple places can prevent this kind of error.

How to successfully return the metadata off of an mp3 file while avoiding a null pointer exception

When I attempt to run the program that takes the metadata and prints it from an mp3 file, I am returned with an "Exception in thread "main" java.lang.NullPointerException at project.mp3MetaData.main(musicdj.java:18)". For this class you need the jid3lib jar. How do I avoid this exception and do I need to pass any variables through the tags at the bottom?
package 1234;
import java.io.File;
import java.io.IOException;
import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;
public class mp3MetaData {
public static void main(String[] args) throws IOException, TagException {
// TODO Auto-generated method stub
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
MP3File mp3file = new MP3File(sourceFile);
ID3v1 tag = mp3file.getID3v1Tag();
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}
Any help will be greatly appreciated.
Your MP3 file might not contain an ID3 tag. So check whether tag is null or not, before using it. Something like this:
public static void main(String[] args) throws IOException, TagException
{
File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
final MP3File mp3file = new MP3File(sourceFile);
final ID3v1 tag = mp3file.getID3v1Tag();
if (null == tag)
{
System.out.println("No ID3 tag found!");
}
else
{
System.out.println(tag.getAlbum());
System.out.println(tag.getAlbumTitle());
System.out.println(tag.getTitle());
System.out.println(tag.getComment());
}
}

Reading multiple files in directory and printing specific content

What I am trying to achieve is basically a Java file which looks through a specific directory on the users computer, search all the files in the directory for specific word (in this case an email) and then at the end print them out.
The current script of which I have now, looks for all the files in a certain directory, prints out those file names. As well as that I have also figured out how to have that script search through one file for a specific word and then print it out. The only problem is that although it searches through that one file and gets that word/phrase it has to be given the full directory and file to work. I just want it to have a specific directory and then search all the files in it. I have tried doing this using the directory variable of which I have created to find all files, but it does not work when using that as the directory for the files to search through to find the word(s).
Here underneath is the part of my code which is used for the function I want. The actual function is called in my real script so don't worry about that as it is working. I have also just commented in the script what variable I want to work where.
package aProject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2"); // this is the right directory I want to look through
public static void listFilesForFolder(final File foldersMac) {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
try {
BufferedReader bReaderM = new BufferedReader(new FileReader("/Users/username/Library/Mail/V2/AosIMAP-/INBOX.mbox/longnumber-folder/Data/Messages/1.emlx")); //this is where I would like the foldersMac variable to work in, instead of this full directory
String lineMe;
while((lineMe = bReaderM.readLine()) != null)
{
if(lineMe.contains(".com"))
System.out.println(lineMe);
}
bReaderM.close();
}
catch (IOException e) {
}
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I think this is what you're trying to achieve:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersMac);
}
public static void listFilesForFolder(final File foldersMac) throws IOException {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader bReaderM = new BufferedReader(new FileReader(fileEntry))) {
String lineMe;
while ((lineMe = bReaderM.readLine()) != null) {
if (lineMe.contains(".com")) {
lines.add(lineMe);
}
}
}
if (!lines.isEmpty()) {
System.out.println(fileEntry.getAbsolutePath() + ":");
for (String line : lines) {
System.out.println(" " + line.trim());
}
}
}
}
}
}
I think your problem lies around your recursion logic,
You go down recursively in the directory structure, you walk through you tree, but write out nothing cause of this if statement:
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
...
}
Close that If statement earlier, then it should work.

Files.copy throws java.nio.file.NoSuchFileException even though the file to be copied definitely exists

I have a problem with a seemingly simple application.
What it should do:
-Read out the files (*.jpg) of a (hardcoded) directory
-Use the contained Metadata (gotten via implemented Libraries) of said jpgs to generate directories (./year/month/)
-copy the files into the corresponding directories.
What it doesn't:
-copy the files into the corresponding directories BECAUSE it doesn't find the original files (which it read out itself previously). I honestly have no clue why that is.
Here the sourcecode:
package fotosorter;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
public class Fotosorter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JpegProcessingException, IOException {
File startdir = new File(System.getProperty("user.dir"));
FileFilter jpg = new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getAbsoluteFile().toString().toLowerCase().endsWith(".jpg");
}
};
File dir = new File(startdir, "bitmaps"+File.separator+"java-temp");
if (!(dir.exists() && dir.isDirectory())) {
if (!dir.mkdir()) {
throw new IOException("kann das Verzeichnis nicht erzeugen ");
}
}
File[] files = new File(startdir, "" + File.separator + "bitmaps" + File.separator + "java-fotos").listFiles(jpg);
for (File file : files) {
Metadata metadata = JpegMetadataReader.readMetadata(file);
ExifIFD0Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
String[] dates = directory.getDate(ExifIFD0Directory.TAG_DATETIME).toString().split(" ");
File year = new File(dir, dates[5]);
File month = new File(year, dates[1]);
File fname = new File(month, file.getName());
if (!(month.getParentFile().exists() && month.getParentFile().isDirectory())) {
if (!month.mkdirs()) {
throw new IOException("kann die Verzeichnisse nicht erzeugen");
}
}
copyFile(file, fname);
}
}
public static void copyFile(File from, File to) throws IOException {
Files.copy(from.toPath(), to.toPath());
}
}
And here the full exception it throws:
run:
Exception in thread "main" java.nio.file.NoSuchFileException: D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-fotos\cimg2709.jpg -> D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-temp\2008\Sep\cimg2709.jpg
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:205)
at sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:277)
at java.nio.file.Files.copy(Files.java:1225)
at fotosorter.Fotosorter.copyFile(Fotosorter.java:64)
at fotosorter.Fotosorter.main(Fotosorter.java:59)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
As you may have guessed it's not finished yet. Apart from solving my previously stated problem I still have to put it into methods.
Make sure that the input file exists.
But also make sure that the path of the destination folder does exist.

Servlet does not open txt

Servlet is very good looking and reading files that have English names like hello.txt. It does not want to read files that have a Russian name, such pushkin.txt. Is anyone able to help to solve this problem?
Here is the code:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
#SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
finally {
if(reader != null) {
try{
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
The question is relevant, the problem is not solved
I thought that you have a problem whith the statements
for (String string : files) {
if (myName.equals(string)) {
I would compare in this way
for (File file: files) {
if (myName.equals(file.getName())) {
I hope that it help you.
Note: Thanks for the comments, you can try it.
Greetings
First of all I would use a debugger to check what's wrong with that code. It's quite difficult to find a bug without running the code. If you don't want to use a debugger print out all filenames found in the directory to ensure that some file names were found:
for (String string : files) {
System.out.println(string)
....
If files were found I would check whether I have rights to write to them. It might be that the application has not proper permissions to write in selected directory.
Are files "hello.txt" and pushkin.txt directly inside "C:\Users\vany\Desktop\test\" folder? Or is pushkin.txt file in another folder from "C:\Users\vany\Desktop\test\"?
Can you show us how you invoke the servlet?
If you have pushkin.txt in another folder and you invoke the servlet with something like "folder\pushkin.txt" it will not work because getFileNames() returns file names (without folder) and "myName.equals(string)" fails as "folder\pushkin.txt" is not equal to "pushkin.txt"

Categories

Resources