I have a program which replaces text in a file based on command line input. Currently it creates a temporary file, and writes the string with the replaced text in the new temporary file. This program works on a desktop in a computer lab on my campus, but when I try to run it on my personal laptop, the temporary file is created, I can find it by printing its canonical path, and file.exists() returns true, but it does not show up on my desktop.
A search using Windows Explorer yields nothing.
I am running Windows 7 and using TextPad. Does anyone know what might be causing this? I can supply any other necessary information.
Edit: I am running Windows 7 on a Mac Pro 2011, if that makes any difference at all.
Edit: I discovered the problem. I had downloaded Comodo Antivirus software and whenever I created a file it would create it in a VTRoot folder for sandbox purposes. I was able to alter the settings and solved my issue.
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
}
}
}
If you could not see the temp.txt file it is because it is located in your project directory where your java source code are located.However if you will found it then also it will contain nothing.The reason being you have not closed the output stream to file just place
output.close()
after the while loop.
Try to create file by providing entire file path while creating like
File(URI uri)
This creates a new File instance by converting the given file: URI into an abstract pathname.
I discovered the problem. I had downloaded Comodo Antivirus software and whenever I created a file it would create it in a VTRoot folder for sandbox purposes. I was able to alter the settings and solved my issue.
If you have installed comodo antivirus then you should follow the instruction :
1.Open the comodo,
2.Click on the settings,
3.Then click on the Containment -> click on the Auto-containment,
4.Then at the top, uncheck the enable auto-containment.
Related
I am working on a game in Java and I have a class that reads an audio file as InputStream and then plays that file through AudioPlayer.
I keep getting a file not found exception.
I have tried placing the audio files in many different locations, and nothing has worked.
This is my class code:
public void play(String string,int sleep) throws IOException
{
//this part does not recognize file
try {
//System.out.println(System.getProperty());
AS = new AudioStream(new FileInputStream(string));
AD = AS.getData();
loop = new ContinuousAudioDataStream(AD);
}
catch(IOException error){
System.out.print(string +" file not found");
}
AP.start(loop);
}
I pass a string like ("audio/beginning.wav")
You are using a path that is relative to the working directory defined when your program runs.
If you are running the program from Eclipse, by default it's the root directory of your program (top-level folder of the program). So normally placing the file in program_folder/audio/beginning.wav should work.
However, the working directory can be changed in the Run Configuration that you are using in Eclipse to run the program: go to the tab Arguments, and you'll find Working directory.
To debug the problem, check the output of the following:
System.out.println(new File("").getAbsolutePath());
Another option is to use the absolute path of the file.
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I know that you must add command line arguments into the "Run Configurations" in Eclipse to get your command line arguments to be passed every time by default. This worked fine on my PC.
The purpose of this question is to create a simple program that can be submitted to an online programming challenge site (like codeeval). The system provides a file path to the command line args[0] and then you manipulate the file and its data.
On the PC I had my Class folder > Default Package > (file.txt and TestCode.java)
The project was set up with a run configuration with simply file.txt in the program arguments section.
On the MAC this doesn't seem to be working. I get a fileNotFoundExcepion. I'm new to MAC so I'm thinking this might be a problem with file extensions not being what I think they are. I saved a file as "file.txt" but if I save it as "file" MAC doesn't show the file extensions and I'm not sure if MAC supports .txt by default.
If it doesn't support .txt, what file type is a "text document"? I tried saving the text document as "file" leaving off any extension, and then adding file.rtf or file.txt or even file to the Program arguments and none of that works. It all gives me a fileNotFoundException.
EDIT
The intent is to be able to develop solutions to the CodeEval (or similar) website and submit them. I have previously solved many problems on CodeEval and turned them in with the code below from a PC. This, however, doesn't work on MAC. The answer involving the use of the URL does not work when run from the solution checking platform (presumably because the program is not actually saved onto the system).
EDIT 2
My entire program:
public class TestCode {
public static void main (String[] args)throws IOException{
File filename = new File(args[0]);
Scanner file = new Scanner(filename); // returns the fileNotFoundException
while( file.hasNextLine()){
String line = file.nextLine();
System.out.println(line);
}
}
}
Under "Run Configurations" in the Arguments tab > Program Arguments I have tried putting file, file.txt, file.rtf all three with a "text document" in the same directory as the above program. I have tried naming that file file, file.txt and file.rtf And i tried every combination of these names.
Did you try to use the absolute file name as command line parameter? This should be something like /Users/name/path/to/your/file. If the file is part of your project, you can also use a variable such as ${project_loc}/file (try the button Variables… below the Program Arguments field.
Replace your code with this
URL resource = TestCode.class.getResource(args[0]);
Scanner file = new Scanner(new File(resource.getFile()).getAbsoluteFile());
i want to ask you regardless finding the file path...
I have, or i would have files that will be associated with my app, but i dont know how to find out the file path that initializes opening my app.
For example:
If i click in windows enviroment on excel file "file.xlx", windows will open excel application with this file "file.xls" and i want exactly the same. After my app will be open, i want to know file path that inicializes my app to start...
I hope that my question is understandable and i apologize for my bad english.. :)
Edit:
I try add some another example...
I try describe some logic operations...
1 - nothing is running, only windows - i hope :)
2 - user click on some file that is somewhere in the HDD ( this file can have different name and different location )
3 - this file with some extension has associated start with my app
4 - app automatically find out on whitch file user clicked ( who invoke the launch of my application ) and use this file path on other work...
I think that should be something like when i start console app. with some argument....but this argument i must get from some windows location.
Just like when i click on file.txt and windows will open notepad and notepad will have automatically open this file.txt, or i click on file.dbf and windows will open the foxpro with this file
I want click on file.xxx and my app will open and work with this file automatically, so there i think must be some way how to get this file location on which i clicked...
I hope this help...
Look at the java system properties http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html, you probably want user.dir
i think what you need is a program like this , this will calculate the existance of your file in side the given directory
package fileSearch;
import java.io.File;
import java.io.FilenameFilter;
public class fileSearch {
/**
* #param args
*/
public static void main(String[] args) {
fileSearch obj = new fileSearch();
obj.finder("program.txt");
for(int i=0;i<obj.finder("C:/Users/hussain.a/Desktop").length;i++)
{
System.out.println(obj.finder("C:/Users/hussain.a/Desktop")[i].getName());
}
}
public File[] finder( String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
} );
}
}
now its up to you to apply to your desired directory , if you want it to exactly like the windows program , then you will have to use root directory every time and pass the file name as a parameter replacing ".txt" in this program
hope it serves , rest is up to you to implement it
I think you can set the os,like the registry,when you installing the app.
String osName = System.getProperty("os.name") ;
I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].