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.
Related
I'm trying to move a file with processing.
import java.util.Base64;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
String source = "C:\test\1.jpeg";
String newdir = "C:\test123\1.jpeg";
void setup() {
Files.move(source, newdir.resolve(source.getFileName()));
}
I took a look at this and tried to make it work, however I get an error that The function getFileName() does not exist. I looked for this also, but didn't find much. Could someone point me into the right direction for moving a file from one dir to another?
Take a look at this:
import java.nio.file.*;
String source = "C:\\test\\1.jpeg";
String newdir = "C:\\test123\\1.jpeg";
void setup() {
try {
Path temp = Files.move(Paths.get(source), Paths.get(newdir));
} catch (IOException e) {
print(e);
}
}
Couple of points - use \\ instead of a single \ when specifying the paths. Secondly, getFileName() can only be applied to a Path object, not a String, and that caused your error in the question. Same, by the way, with the resolve(String s) method, it can only be applied to a Path, not String.
Using Paths:
import java.nio.file.*;
Path source = Paths.get("...");
Path newdir = Paths.get("...");
void setup() {
try {
Files.move(source, newdir);
} catch (IOException e) {
print(e);
}
}
I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}
So I am working on this game where I have a high score stored in a text file. I am following the newboston's tutorial on how to read and write to file. Right now I am testing whether the read class works and it is not working. It says cannot find file when I put the text exactly like how it is and the file is in my package so I don't have to say a path. Here is the method code in my game using both read and write classes:
private int getHighScore(int change, int newScore) {
if (change==1) {
readFile r=new readFile();
r.openFile();
String fileScore=r.readtext();
r.closeFile();
int score=Integer.parseInt(fileScore);
return score;
}
else {
writeToFile w=new writeToFile();
w.openFile();
w.addRecords(newScore);
w.closeFile();
return newScore;
}
}
Here is the read class:
import java.io.*;
import java.util.*;
public class readFile {
private Scanner read;
public void openFile() {
try {
read=new Scanner(new File("highScore.txt"));
}
catch(Exception e){
System.out.println("Could not find file.");
}
}
public String readtext() {
String score=read.next();
return score;
}
public void closeFile() {
read.close();
}
}
Also here is the write file. I am concerned that this class might not work either as it looks like it maybe creating a new file and writing to that new one when I just want to write to an existing file I already have called "highScore.txt" Anyways here is the write class:
import java.util.*;
public class writeToFile {
private Formatter x;
public void openFile() {
try {
x=new Formatter("highScore.txt");
}
catch(Exception e) {
System.out.println("Can not open that file.");
}
}
public void addRecords(int newScore) {
String score=""+newScore;
x.format("%s", score);
}
public void closeFile() {
x.close();
}
}
So I am wondering why it is not working and thanks in advance.
If your file exists in the same location where ReadFile and WriteFile exists. Then you can use the below code.
URL url = getClass().getResource("highScore.txt");
Scanner read=new Scanner(new File(url.getPath()));
Ok I solved it. The problem was wrong location and I still did not have to give a path. So basically I looked at this thread: The system cannot find the file specified in java
The part of the thread is listing the files in the directory. When I did that, I noticed everything it mentioned was in the project folder. I moved my file from the src folder to the project folder and it worked. So if you come across a problem where you know you spelled the file name right but get file does not exist, make sure that your file is in the project folder and NOT in the src folder.
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"
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 */
}
}