I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.
Related
I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});
This question already has answers here:
To create a new directory and a file within it using Java
(2 answers)
Closed 4 years ago.
I want to write a new file inside a folder that currently does not exist.
I use it like this:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
I get the file filename.txt under a folder called dir1.dir2.
I need dir1/dir2:
How can I achieve this?
Please do not mark this question as duplicate because I didn't get what I need after a reseach.
UPDATE 1
I am using Jasper Report with Spring Boot to export a pdf file.
I need to create the file under a directory name the current year. Under this folder, I need to create a directory called the current month, and under this directory the pdf file should be exported. Example :
(2018/auguest/report.pdf )
I am using LocalDateTime to get year and month
Here is a portion of my code :
ReportFiller reportFiller = context.getBean(ReportFiller.class);
reportFiller.setReportFileName("quai.jrxml");
reportFiller.compileReport();
reportFiller = context.getBean(ReportFiller.class);
reportFiller.fillReport();
ReportExporter simpleExporter = context.getBean(ReportExporter.class);
simpleExporter.setJasperPrint(reportFiller.getJasperPrint());
LocalDateTime localDateTime = LocalDateTime.now();
String dirName = simpleExporter.getPathToSaveFile() + "/"+
localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File dir = new File(dirName);
dir.mkdirs();
String fileName = dirName + "/quaiReport.pdf";
simpleExporter.exportToPdf(fileName, "");
Here is what I get :
Try below code which will work as per your expectation
File dir = new File("C:\\Users\\username\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newFile = new FileWriter(file);
You need to create folder structure first and file next
You need to create directory first then create file:
Like this:
String dirName = "/" + localDateTime.getYear() + "/" + localDateTime.getMonth().name();
File file = new File(dirName);
file.mkdirs();
file = new File(file.getAbsolutePath()+"/quriReport.pdf");
file.createNewFile();
If you go your project directory you see 2018/August/quriReport.pdf
But IDE show subfolder with . if there is only one subfolder.
At first, create the directories, then create a new file to write.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class TestDir {
public static void main(String[] args) {
String dirPath = "C:\\user\\Desktop\\dir1\\dir2\\";
String fileName = "filename.txt";
Path path = Paths.get(dirPath);
if(!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(dirPath + fileName), "utf-8"))) {
writer.write("something");
} catch (IOException e) {
e.printStackTrace();
}
}
}
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
Files.createDirectories(file.getParentFile().toPath());
FileWriter writer = new FileWriter(file);
writer.write("jora");
writer.close();
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);
I have a file and inside it has some tables and my question is how can I create a new file but in this file it includes both tables and additional information. I tried in terminal but I could not find it, help me please...
How do you want to check when to create a new file, when is the next text called ?
How about to use JFileChooser, just choose or create a new file ?
Maybe something like this:
private void createNewFile() {
File newFile;
File nf = null;
String nt = "someName";
if((newFile = new File(DirectoryPath.toString())).exists()) { //it must be a directorypath to create a new file in it.
nf = new File(DirectoryPath, "withAverage" + nt + ".txt"); //create a new file
nf.createNewFile();
} averageFile = nf;
}
private void fileWriterInput() {
FileWriter fw = new FileWriter(averageFile);
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.newLine();
bw.append(inputString);
bw.append("----------------------------------");
bw.flush();
}
}
I have a filename in my code as :
String NAME_OF_FILE="//sdcard//imageq.png";
FileInputStream fis =this.openFileInput(NAME_OF_FILE); // 2nd line
I get an error on 2nd line :
05-11 16:49:06.355: ERROR/AndroidRuntime(4570): Caused by: java.lang.IllegalArgumentException: File //sdcard//imageq.png contains a path separator
I tried this format also:
String NAME_OF_FILE="/sdcard/imageq.png";
The solution is:
FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE)); // 2nd line
The openFileInput method doesn't accept path separators.
Don't forget to
fis.close();
at the end.
This method opens a file in the private data area of the application. You cannot open any files in subdirectories in this area or from entirely other areas using this method. So use the constructor of the FileInputStream directly to pass the path with a directory in it.
openFileInput() doesn't accept paths, only a file name
if you want to access a path, use File file = new File(path) and corresponding FileInputStream
I got the above error message while trying to access a file from Internal Storage using openFileInput("/Dir/data.txt") method with subdirectory Dir.
You cannot access sub-directories using the above method.
Try something like:
FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt"));
You cannot use path with directory separators directly, but you will
have to make a file object for every directory.
NOTE: This code makes directories, yours may not need that...
File file= context.getFilesDir();
file.mkdir();
String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
file=new File(file,array[t]);
file.mkdir();
}
File f=new File(file,array[array.length-1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);
String all = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null){
all = all + strLine;
}
} catch (IOException e) {
Log.e("notes_err", e.getLocalizedMessage());
}
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for(int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file,array[array.length- 1]);
RandomAccessFileOutputStream rvalue =
new RandomAccessFileOutputStream(f, append);
I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!
public class MyClass {
private String state;
public File myFilename;
#Override
protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(state)) {
myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
if (!myFilename.exists()) {
myFilename.mkdirs();
}
}
}
public void myMethod {
File fileTo = new File(myFilename.toString() + "/myPic.png");
// use fileTo object to save your file in your new directory that was created in the onCreate method
}
}
I did like this
var dir = File(app.filesDir, directoryName)
if(!dir.exists()){
currentCompanyFolder.mkdir()
}
var directory = app.getDir(directoryName, Context.MODE_PRIVATE)
val file = File(directory, fileName)
file.outputStream().use {
it.write(body.bytes())
}