Why user.home returns "\" not "/"? - java

Maybe some of you will tell me where the mistake is, because I'm sitting on this for a few hours and didnt see anything.
The program should check if the if can be found in a txt file and return it to the bottom.
The second question about user.home
When I use it gets "C: \ Users \ Daniel / test / Test.java" by which the program does not work when I set the path to "C :/ Users / Daniel / test / Test.java" program begins to find my .txt file, but i cant leave it like that it must be found by user.home :(
public class Main {
public static void main(String ... args) throws Exception {
String usrHome = System.getProperty("user.home");
Finder finder = new Finder(usrHome + "/Testy/Test.java");
int nif = finder.getIfCount();
System.out.println("Number found 'if'": " + nif);
}
}
And finder class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Finder {
String file;
Finder(String file){
file = this.file;
}
int getIfCount() throws FileNotFoundException{
int count = 0; String tmp; String lf = "if";
Scanner sc = new Scanner (new File("C:/Users/Daniel/Testy/Test.java"));
while(sc.hasNext()){
tmp = sc.next();
System.out.println(tmp); //to check if it works correctly
if(tmp == lf){
count++;
}
}
sc.close();
return count;
}
}
The result should look like this:
Number found "if": 3
Because there are three such elements, although the result is always 0

the result is always 0
Because you use == with String, try to Use equals() when you compare two string
if (tmp.equals(lf)) {
count++;
}

A better way to do the filename concatenation would be this:
File home = new File(System.getProperty("user.home"));
File file = new File(home, "Testy/Test.java");
/* Or even ...
File file = new File(new File(home, "Testy"), "Test.java");
*/
Finder finder = new Finder(file);
This avoids needing to know about the platform pathname representation.
The miscounting issue is caused by a basic Java 101 mistake. You are using '==' to compare Strings. It (usually) doesn't work. Use String.equals(...).

Related

Recursion Java vs Python

last week i made this java file wondering to search in my pc files which contains certain words i input.
After to have done it i thought "why not translating it in python?" and in python i have seen that it runs out of memory (because of the recursion), but in java didn't (in python the code works if i dont give a lot of dirs and files), i put here the 2 codes and the error (java vs python) so u can help me(sorry for my english i am not mother tongue).
JAVA:
package com.company;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input path to start(remember the / at the end):");
Scanner input = new Scanner(System.in);
String path=input.nextLine();
ArrayList<String> words= new ArrayList<>();
String word="";
while(!word.equals("//quit")){
System.out.println("Input word to search (input://quit to stop):");
word=input.nextLine();
if(!word.equals("//quit"))
words.add(word);
}
Finder finder= new Finder(path,castToArray(words));
finder.readFile();
}
private static void readFiles(Finder finder){
String[] files = finder.printFiles();
for(int i=0; i< files.length;i++){
System.out.println(files[i]);
}
}
private static String[] castToArray(ArrayList<String> words){
String[] w0rds = new String[words.size()];
for(int i=0; i< words.size(); i++){
w0rds[i]= words.get(i);
}
return w0rds;
}
}
class Finder {
private String[] words;
private File file;
private String path;
Finder(String path,String... words){
this.words=words;
this.path=path;
file= new File(path);
}
public String[] printFiles(){
String[] files;
files=file.list();
return files;
}
public void readFile(){
String[] files= printFiles();
for(int i=0; i< files.length;i++){
File f = new File(file.getPath()+"/"+files[i]);
if(!f.isDirectory()){
searchWord(f,words);
}else {
Finder finder = new Finder(path+f.getName()+"/",words);
finder.readFile();
}
}
}
public File getFile() {
return file;
}
public void searchWord(File file,String... words){
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(file));
byte[] bytes = new byte[512];
dis.readFully(bytes);
String obj = new String(bytes);
for(int i=0; i< words.length;i++){
if(obj.contains(words[i])){
System.out.println(file.getName());
break;
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
PYTHON:
import os
class Finder:
path = ""
words= []
def readFile(self,path,words):
new_file = open(path, "r")
data=new_file.read(8192)
new_file.close()
for word in words:
if(data.find(word,0,len(data))!=-1):
print "name: "+new_file.name+" path: "+path
break
def __init__(self,path, words):
self.path=path
self.words=words
def __del__(self):
files=os.listdir(path)
for file in files:
if(os.path.isdir(path+file)!=True):
self.readFile(path+file,words)
else:
dirpath = path+file+"/"
finder = Finder(path,words)
path= raw_input("input path to start(remember the / at the end):\n")
words=[]
word = ""
while word != "//quit":
word=raw_input("input word to search (write //quit to start searching):\n")
if word != "//quit":
words.append(word);
print "start searching for "+str(words)+"..."
finder = Finder(path,words)
PYTHON ERROR:
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4d40>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4c68>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4d40>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4c68>> ignored
In python, you rarely should use the __del__ method. It is a special magic method that is called at an arbitrary time (when the object is garbage-collected) with very few applications and multiple caveats. Instead, for most use cases, you should use a .close() method you call explicitly or with a context manager like contextlib.closing.
That said, I don't know why you made a __del__ method at all since in your java code there is nothing like that. Closest java thing would be a finalize method, but you're not using it, so why did you chose to use __del__ in your translation?
Anyway, in python you can use os.walk() instead of os.listdir() to traverse your directory tree - os.walk() is iteratively recursive so it can handle any path depth without running out of call stack space:
for pth, dirs, files in os.walk(path):
for filename in files:
self.readFile(os.path.join(pth, filename))
This code snippet will call readFile with all files in all subfolders.
The problem in your python code is, that you use the global path variable in __del__ instead of self.path. Therefore you get an infinite recursion.
Better convert your class into functions:
import os
def readFile(path, words):
with open(path, "r") as new_file:
data = new_file.read(8192)
for word in words:
if word in data:
print "name: {} path: {}".format(new_file.name, path)
break
def search(path, words):
files = os.listdir(path)
for filename in files:
fullname = os.path.join(path, filename)
if not os.path.isdir(fullname):
readFile(fullname, words)
else:
search(fullname, words)
path = raw_input("input path to start: ")
words = []
while True:
word = raw_input("input word to search (write //quit to start searching): ")
if word == "//quit":
break
words.append(word)
print "start searching for {}...".format(', '.join(words))
search(path, words)

reading txt file and writing a dictionary

My objective is to eventually make a spell checker but I need a dictionary of words to do that.
Here I'm trying to allow the user to input any number of text files as long as there's a space in between the file names ("novel1.txt novel2.txt novel3.txt").
I will use every word from these novels to write to a .dat file of individual words on individual lines(i.e. a dictionary of words). However I'm getting a file not found error at Scanner read = new Scanner(new File(filenames[i])); even though I know that I have the file.
I have even tried putting it in the source package to make sure it could be found.
At the very bottom of my code is a small test I ran (commenting out the other code first) and it does indeed print "war.txt isn't a file," even though I can clearly see that I have the txt file and have typed it correctly.
Can somebody tell me why java isn't seeing my txt file or maybe doesn't think it is a normal file?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}
I believe you do something in a wrong way. Try following example and compare it with your actual file locations.
Demo.java
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
compile and run it
javac Demo.java
java Demo
output
war.txt isn't a file.
now create in the same directory the war.txt
echo "foobar" > war.txt
run the code again
java Demo
output
war.txt is a file.
For the FileNotFoundException make sure that files are in your classpath if you insert only the filenames (for example if you use eclipse put the files on the root folder of the project).
For the war.txt issue you should do this:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
This because when you do File war = new File("war.txt"); you are not creating the file, you have to explicitily create it with war.createNewFile();.
Finally, pay attention here:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
You do two times read.next() without check read.hasNext() the second time. You should write something like that:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}

How to access directory with full file path?

So, I'm writing a program that needs to iterate through all files in a directory and here is what I currently have.
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
VotingData v = new VotingData();
Scanner in = new Scanner(System.in);
System.out.print("Please input a directory.");
String input = in.next();
File dir = new File(input);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
v.merge(RecordReader.readRecord(child.toString()));
}
}
else {
// do nothing right now.
}
String[] sub1 = {"Montgomery","Miami"};
TextualRepresentation.toString(v.getAllResults());
TextualRepresentation.toString(v.getCountyResults("Montgomery"));
TextualRepresentation.toString(v.getCountyResults("Miami"));
TextualRepresentation.toString(v.getCountyResults("Butler"));
TextualRepresentation.toString(v.getSubsetResults(sub1));
}
}
The filepath of the project is C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff.
The input I'm trying is "C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles" , but it doesn't seem to work. However, when input is just "TestFiles" it does. I want to be able to access directories in different folders, but for some reason the long method isn't working.
Edit: I don't know what the error is. All I know is when I put "TestFiles" into the Scanner it works fine and when I try the full file path it doesn't crash, but it doesn't yield the results I want.
Scanner#next() reads white-space delimited (by default) string tokens.
Your input:
C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles
Contains spaces, so next() just reads "C:\Users\Jarrett".
You can use Scanner#nextLine() instead.
In the future, to debug on your own, either step through in a debugger to see what values variables have, or add print-outs to verify, e.g. this would have led you to a solution quickly:
System.out.println("input was " + input);

Java not detecting file contents

I'm having difficulty figuring out why this isn't working. Java simply isn't executing the while loop, file apparently does not have a next line.
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
Here is the file I am testing this with. I got it to work with the first few paragraphs but it seems to simply stop working...:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"
He took his vorpal sword in hand:
Long time the manxome foe he soughtó
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!
One, two! One, two! and through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.
"And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!"
He chortled in his joy.
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
——from Through the Looking-Glass, and What Alice Found There (1872).
/*
* Lab13a.java
*
* A program that prompts the user for an input file name and, if that file exists,
* displays each line of that file in reverse order.
* Used to practice simple File I/O and breaking code up into methods as well as a first
* step to implementing Lab13b.java - reversing the entire file and Lab13c.java writing
* output to a separate output file.
*
* #author Benjamin Meyer
*
*/
package osu.cse1223;
import java.io.*;
import java.util.*;
public class Lab13a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String fileName = "";
Scanner file;
boolean pass = false;
while (!pass) {
try {
fileName = getFileName(keyboard);
file = new Scanner (new File (fileName));
pass = true;
String currentLine;
while (file.hasNextLine()) {
currentLine = file.nextLine();
System.out.println(reverse(currentLine));
}
}
catch (FileNotFoundException e) {
System.out.println("There was a problem reading from " + fileName);
System.out.println("Goodbye.");
return;
}
}
}
// Given a Scanner as input prompts the user to enter a file name. If given an
// empty line, respond with an error message until the user enters a non-empty line.
// Return the string to the calling program. Note that this method should NOT try
// to determine whether the file name is an actual file - it should just get a
// valid string from the user.
private static String getFileName(Scanner inScanner) {
boolean pass = true;
String fileName = "";
while (pass) {
System.out.print("Enter an input name: ");
fileName = inScanner.nextLine();
if (fileName.length()!=0) {
pass = false;
}
else {
System.out.println("You cannot enter an empty string.");
}
}
return fileName;
}
// Given a String as input return the reverse of that String to the calling program.
private static String reverse(String inString) {
if (inString.length()==0) {
return "";
}
String reversed = "" + inString.charAt(inString.length()-1);
for (int x = inString.length()-2; x>=0; x--) {
reversed = reversed + inString.charAt(x);
}
return reversed;
}
}
The issue might lie in your implementation of your functions getFilename() or reverse(). Since you have stated that you got it to work with a few of the paragraphs I doubt that your program is failing due to your file handling. It might be in the logic you are using to reverse the strings in the file that is causing the issue.

File that exists is not being found in Java

I have a Java program that searches through your cookies files and then saves each file into an array. I then try to search through each of those files for a certain string, however when I try to search the files I KNOW exist, java tells me that they don't. Any ideas?
Here is my code so far:
import java.io.*;
import java.util.*;
public class CheckCookie
{
static String[] textFiles = new String[100];
static String userName = "";
public static void findCookies()
{
String path = "pathtocookies";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
textFiles[i] = files;
}
}
}
}
public static boolean searchCookies()
{
for(int j = 0; j < textFiles.length; j++) {
String path2 = "pathtocookies"+textFiles[j];
File file = new File(path2);
try {
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.contains("ineligible_age")) {
System.out.println("A cookie for ineligible age was set.");
return true;
}
}
}
catch(FileNotFoundException e) {
System.out.println("File was not found.");
return false;
}
}
System.out.println("A cookie for ineligible age was not set.");
return false;
}
public static void main(String[] args)
{
findCookies();
searchCookies();
System.out.println();
System.out.println("Finished searching for cookies. Yum.");
}
}
Actual path:
C:/Users/lucas.brandt/AppData/Roaming/Microsoft/Windows/Cookies
Use a List, instead of an array to store the textFiles.
Imagine a directory with 2 files. The first is "abc.doc", the second "itsme.txt"
Your textFiles array will look like this:
textFiles[0]: null
textFiles[1]: "itsme.txt"
So you try to access "pathtocookies" + "null" which will fail, you go to the catch and return out of the function.
Further hints:
Return the list from the first function, use it as an argument for the second function
Use a debugger or "debug" print statements to debug your code to see whats happening
More hints depends on the actual use case.
--tb
In this line:
String path2 = "pathtocookies"+textFiles[j];
You are missing the File separator between the directory name and the file name. java.io.File has a constructor that takes the parent path and the file name as separate arguments. You can use that or insert File.separator:
String path2 = "pathtocookies" + File.separator + textFiles[j];
You are also picking up directories in your array. Check that it is a file before you try to scan it.
Also, consider the other answer where the files are saved in a List, eliminating the directories.
files = listOfFiles[i].getName();
Try to change to
files = listOfFiles[i].getAbsolutePath();
EDIT
You can also initiate directectly an array of File (instead of String),
and you have to use .canRead() method to verify File access.
Why don't you just store the File instances in a File[] or List<File>?
I think you would also benefot from using a StringBuilder, when doing a lot of string concatenstions...

Categories

Resources