Hi I'm having a problem creating a folder in which every file I create in my for each loop will be placed. It is a basic problem but I can't seem to see it, any help would be much appreciated!
Scanner inputScan = new Scanner(System.in);
System.out.println("Enter location for output folder to be built..");
String filePath=inputScan.next();
inputScan.close();
File dir = new File(filePath+"subnet_output");
dir.mkdir();
for(String myAddr: addr){
String myFileName = myAddr.replaceAll("/", "-");
File file = new File(dir+myFileName+".txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
You are missing "/" while creating file inside folder:
File file = new File(dir+myFileName+".txt");
Replace with:
File file = new File(dir+File.pathSeparator+myFileName+".txt");
Try PrintWriter.append(...) and PrintWriter.flush() for actually writing into that file you want to create.
File file = new File(dir+"/"+myFileName+".txt");
Related
How do I get a json file I am creating to go into another directory. I am using a method that gives a file name and use this code to create it, its not the full code but Im pretty sure this is the only part I need to modify.
FileInputStream in = new FileInputStream(fileName);
JSONObject obj = new JSONObject(new JSONTokener(in));
right now it puts it in a directory but I want to put it in a folder in that directory.
this also does not work
FileInputStream in = new FileInputStream("/A/Ab/src/serv"+fileName);
///////////////////////////
File cDir = new File("");
FileInputStream in = new FileInputStream(cDir.getAbsoluteFile() +fileName);
Try this:
File dir = new File("/A/Ab/src/serv");
if (!dir.exists()) dir.mkdirs();
then:
FileInputStream in = new FileInputStream("/A/Ab/src/serv/" + filename);`enter code here`
If the directory already exists and you just want to create a new file, then simply do:
FileInputStream in = new FileInputStream(new File("/A/Ab/src/serv/" + filename))
I am new to Stack Overflow and fairly new to programming, so hopefully this makes sense. I am writing a java program that creates a file in a specific directory. My program works on Windows and creates a file in the right location, but it does not work on Mac. I have tried changing the backslashes to a single forward slash, but that doesn't work. How should I change the code so that it works for Mac or ideally for both? I've put some of the code below.
Thanks in advance!
Class that creates new path for file:
try{
//Create file path
String dirpath = new ReWriterRunner().getPath()+"NewFiles";
//Create directory if it doesn't exist
File path = new File(dirpath);
if (!path.exists()) {
path.mkdir();
}
//Create file if it doesn't exist
File readme = new File(dirpath+"\\README.md");
if (!readme.exists()) {
readme.createNewFile();
}
Method that gets user input on where to put file:
public static String getPath(){
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter the directory name under which the project files are stored.");
System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
System.out.println("Use double slashes when typing.");
s = in.nextLine();
return s;
}
you can use system properties to identify the system you are currently operating on ..
more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
but i would prefer using NIO. but that is your choice
https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Forward slash "/" must be used to get the file path here. for ex.> Use:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
I have a directory in my jar called "lessons". Inside this directory there are x number of lesson text files. I want to loop through all these lessons read their data.
I of course know how to read a file with an exact path:
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/lesson1.lsn")));
try{
in.readLine();
}catch(IOException e){
e.printStackTrace();
}
But what I want is something more like this:
File f = new File(Main.class.getResource("lessons"));
String fnames[] = f.list();
for(String fname : fnames){
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/" + fname)));
in.readLine();
}
File however doesn't take a URL in it's constructor, so that code doesn't work.
I will use junit.jar in my test as an example
String url = Test1.class.getResource("/org/junit").toString();
produces
jar:file:/D:/repository/junit/junit/4.11/junit-4.11.jar!/org/junit
lets extract jar path
String path = url.replaceAll("jar:file:/(.*)!.*", "$1");
it is
D:/repository/junit/junit/4.11/junit-4.11.jar
now we can open it as JarFile and read it
JarFile jarFile = new JarFile(path);
...
I've created a random access file as follows:
RandomAccessFile aFile = null;
aFile = new RandomAccessFile(NetSimView.filename, "rwd");
I want to delete the file "afile". can anyone suggest me how to do it?
You can do that:
File f = new File(NetSimView.filename);
f.delete();
Edit, regarding your comment:
The parameter NetSimView.filename seems to be a File and not a String that contains the path to the file. So simply do:
NetSimView.filename.delete();
I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me