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))
Related
I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);
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");
{
headFile = File.createTempFile("HMh", ".tmp");
headCreated = true;
dataFile = File.createTempFile("HMd",".tmp");
dataCreated = true;
headOut = new DataOutputStream((new BufferedOutputStream(new FileOutputStream(headFile))));
dataOut = new DataOutputStream((new BufferedOutputStream(new FileOutputStream(dataFile))));
}
I have this code where headOut is being referenced and writing temp File to headFile, I want to replace the temporary File with the File to be stored in Directory in Windows D Drive so as too see the Files being stored physically . Please help with the code . As it creates multiple Temp File please let know to append the File name with the Date Time value so as it doesent overide existing Temp Files .
long l = new Date().getTime();
File.createTempFile("HMh"+l, ".tmp") It will append timestamps to your file.
Write file on drive.
File file = new File("C:\\filename.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
In DynamicWebProject - Eclipse, How to get File Object for file present in src folder, i mean to say class path.
Below program works fine but new update to file is present in wtpwebapps, instead i want to get changed in file present in src folder of Eclipse only(How to get FileOutputStream for file present in classpath).
String filename1 = "/WEB-INF/classes/server123.properties";
ServletContext context = req.getSession().getServletContext();
String path1 = context.getRealPath(filename1);
System.out.println("PATH 1 IS :"+path1);
FileInputStream fis1 = new FileInputStream(new File(path1));
int ch1;
while ((ch1 = fis1.read())!=-1) {
System.out.print((char)ch1);
}
fis1.close();
FileOutputStream fos = new FileOutputStream(path1);
fos.write("jayesh".getBytes());
fos.close();
you can use getServletContext()/filename in your code i.e.
properties.load(new FileInputStream(getServletContext().getRealPath("/filename")));
or
properties.load(new FileInputStream(getServletContext().getRealPath(/filename")));
Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);