I have the following code:
FileSystem fs = FileSystem.get(context.getConfiguration());
Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(fs.create(filePath2,true)));
writer2.write("Key: " + key.toString() + "\nValue: " + values.iterator().next().getSensCol().toString());
writer2.close();
I'm using the Hadoop library for some of these classes. After I execute it, I see the file is created but there is nothing inside it, any ideas why that might be?
There is not sufficient information for a proper diagnosis, but your code looks correct ... except (maybe) for the path. On a Linux system (at least) a normal user should not be able write a file into the "/" directory.
So, I can suggest a couple of possible explanations:
The file is being written, but not to the directory that you are looking at.
The file open is failing (or the writes are failing) but your application is squashing the exception ... in some code that you haven't shown us.
Ah! It looks like you are using org.apache.hadoop.fs.FileSystem ! (The java.nio.file version of the FileSystem class doesn't have a get method.)
I don't think this changes my answer, apart for the stuff about being able to write to the "/" directory. That could be permissible for a Hadoop FS.
Use a FileWriter together with the BufferedWriter.
Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
FileWriter fileWriter2 = null;
BufferedWriter writer2 = null;
try {
fileWriter2 = new FileWriter( filePath2.toFile() );
writer2 = new BufferedWriter( writer2 );
writer2.write("Key: " + key.toString() );
//if you are going to use an Iterator, you better actually use it.
for ( Iterator iterator = col.iterator() ; iterator.hasNext() ; ) {
writer2.write( "\nValue: " + iterator.next()
.getSensCol().toString() );
}
}
catch ( IOException ex ) {
//Exception handling
}
finally {
writer2.close();
fileWriter2.close();
}
I hope I have helped.
Have a nice day. :)
Related
When I getting something in my code I use a short path like
this.getStylesheets().add("/css/editorTool.css");
but when I writing a new file I give exact paht - like:
File f = new File("D:\\IdeaProjects\\SmartCRM for TB\\EditorTool\\resourses\\html\\test.html");
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(html);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
As i will have to distribute this app among some users I will not be able to garanty that the absolute path to my app will be the same. How i can write it to so that it is like "path_to_the_folder_that_is_contained_in_app + fileName?
you can use system property "user.dir" to get current working path, the code is alike this:
String currentWorkingPath = System.getProperty("user.dir");
String fullPath = currentWorkingPath + File.separator+ fileName;
then the file will be under currentWorkingPath when the program run on any PC.
You can use getResource() method of java.lang.Class<T>
The java.lang.Class.getResource() finds a resource with a given name
Documentation Here
usage:
File file = new File(getClass().getResource("html/test.html").getPath());
Hi guys, I'm trying to pass in a string parameter to write that string to a text file.
However , I seem to be having trouble. It works fine when I compile it in a main method, it creates a file and all the values that I write into it.
However, when I use a method. It doesn't create a file at all, not even with the parameters that i passed in. I am intending to use the method in a servlet.
Below is the method that I created.
public class testWriteFile {
public static void writeToFile (String data) throws Exception {
Date dateNow = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
StringBuilder formatDDMMYYYY = new StringBuilder(sdf.format(dateNow));
File file = new File(formatDDMMYYYY+".txt");
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}
}
May I know what is the problem with the code?
Thanks in advance!
Finally, seems like the issue was resolved when the OP printed
System.out.println(file.getCanonicalPath());
It was in a different directory since the OP was using an IDE.
use a full path ("d:/myfolder/a.txt") - can still keep part of it dynamic like if windows
File f = new File("D:/myfolder/" + formatDDMMYYYY + ".txt");
Or linux/ mac
File f = new File("/myfolder/" + formatDDMMYYYY + ".txt");
Make sure you have write permission on the myfolder and replace it with one you do have by using touch command on linux/ unix like systems in terminal :
touch /myfolder/a.txt
ls -l /myfolder/a.txt
Should show current date for that file
I want to create a file in a new directory using the relative path. Creating the directory "tmp" is easy enough.
However, when I create the file, it is just located in the current directory not the new one. The code line is below.
File tempfile = new File("tempfile.txt");
Have tried this also:
File tempfile = new File("\\user.dir\\tmp\\tempfile.txt");
Clearly I'm misunderstanding how this method works. Your assistance is greatly appreciated.
EDIT: added currently used code line as well as the one I think might work for a relative path to clear up confusion.
File dir = new File("tmp/test");
dir.mkdirs();
File tmp = new File(dir, "tmp.txt");
tmp.createNewFile();
BTW: For testing use #Rule and TemporaryFolder class to create temp files or folders
You can create paths relative to a directory with the constructors that take two arguments: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
For example:
File tempfile = new File("user.dir/tmp", "tempfile.txt");
By the way, the backslash "\" can be used only on Windows. In almost all cases you can use the portable forward slash "/".
String routePath = this.getClass().getClassLoader().getResource(File.separator).getPath();
System.out.println(routePath);
/*for finding the path*/
String newLine = System.getProperty("line.separator");
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(routePath+File.separator+".."+File.separator+"backup.txt"), true));
/*file name is backup.txt and this is working.*/
Let say you have "Local-Storage" on your project folder and you want to put a text or whatever file using file write.
File file = new File(dir,fileName ); //KEY IS DIR ex."./local-storage/" and fileName='comp.html'
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
Good Day!
I wrote the method in Java which must search files in folders and do some operations with them.
So the problem is that when I try to check what I have (file or dir) I receive nothing in both cases! But as i can see paths look correct.
How can I fix this problem?
Here is the code:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}
For example this.fileName consists path to folder ( and this folder consists one folder and 2 files).
I got next:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false
Ok. Program says that.
Lets print next code as an example.
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());
Program will print ”True”.
This part makes no sense:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
Even if we forget about the double separator for the time being, it makes no sense to first construct the file name by adding namesOfFilesDir[i], then construct a File() object using the two-argument constructor which basically adds namesOfFilesDir[i] once more. Try printing f.getAbsolutePath() and you'll see what I mean. It should have probably been something like:
File f = new File( normalPath, namesOfFilesDir[i] );
Probably the file doesn't exist, so it is neither a file nor a directory. Try printing the output of f.exists() as well.
Did you notice the duplicate file separator in your path?
I think that perhaps your paths are not correct. Both isFile() and isDirectory() only return true if the file/directory actually exists. Have you tried calling exists() on the file? Also, I'm suspicious of what your getNormalPath() method is doing - I think it might be mangling the filenames.
The 1st System.out.println is missleading!
It would have been better to output the path of f.
Anyway, according the output:
FileName=Readme.txt, Path=[C:\workspace\Grep\t\Readme.txt]
f will be C:\workspace\Grep\t\Readme.txt\Readme.txt
that is, namesOfFilesDir[i] is being appended twice!
It would be easier/better to work just with instances of File directly:
File inputFile = new File(this.fileName);
File[] files = inputFile.listFiles();
for (File f : files) {
System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
//Some other code
}
I am trying to create a back up file for an html file on a web server.
I want the backup to be in the same location as the existing file (it's a quick fix). I want to create the file using File file = new File(PathName);
public void backUpOldPage(String oldContent) throws IOException{
// this.uri is a class variable with the path of the file to be backed up
String fileName = new File(this.uri).getName();
String pathName = new File(this.uri).getPath();
System.out.println(pathName);
String bckPath = pathName+"\\"+bckName;
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream (bckFile);
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
But if instead I was to set bckPath like this, it will work.
String bckPath = "C://dev/server/tomcat6/webapps/sample-site/index_sdjf---sd.html";
I am working on Windows, not sure if that makes a difference.
The result of String bckPath = pathName+"\"+bckName;
is bckPath = C:\dev\server\tomcat6\webapps\sample-site\filename.html - this doesn't result in a new file.
Use File.pathSeparator, that way you dont need to worry what OS you are using.
Try to use File.getCanonicalPath() instead of plain getPath(). This helps if the orginal path is not fully specified.
Regarding slashes, / or \ or File.pathSeparator is not causing the problem, because they are all the same on Windows and Java. (And you do not define bckFile in your code, only bckPath. Also use getCanonicalPath() on the new created bckPath.)