Is it posibble to save class File object in other directory?
I send this class File object from Client directory to server directory by objectOutputStream.
My question is how to create in server directory this class File object.
File f=(File)objectInputStream.readObject();
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
path1=Paths.get(path+name); //name is a directory for this special client name
File a= new File(path1.toString());
That's not what File does.
File is, basically, a euphemism for 'String'. A file object contains 1 field, of type string, with the full path to the field. It represents 'a way to read that file' and not the file itself. If you try to serialize it via ObjectOutputStream, all that you're transferring is the file's name. Not the contents.
You're going to have to transfer the actual bytes across the wire if you want to transfer the contents.
Related
In java, when we create a file, we create files using the name of the extension.
For example :
File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
For example :
File file = new File("D:/light");
This answer assumes you're doing more than just creating a File object - that you're actually creating a file on the file system. (A File object is just a logically representation of a file system entry which may or may not exist.) If you're really just creating a File object, read EJP's answer - at that point, you've basically just got a name. That doesn't have a "type" or a "format".
The extension is just part of the name. The operating system may try to use that to display a different icon, or launch a specific application when you double-click on the icon, or whatever - but it's really just part of the name.
Fundamentally, a file consists of:
The name you specify when you create it
The bytes you write in it
Metadata such as access control
Unless you deliberately add metadata, it's typically just inherited (default permissions etc).
You can write any data in any file - just because a file has an extension of .txt doesn't mean it's definitely a text file. It could have content which is actually MP3-encoded audio data, for example. Whether the OS uses the file extension or the content to work out what to do with the file is up to the OS.
What type of File is created when we create new File without the extension?
No file is created at all, and there is only one type of File.
In java, when we create a file, we create files using the name of the extension.
Or not.
For example: File file = new File("D:/light.txt");
I would like to know what type of file format do we get when we create a file without the file extension type.
You don't. You don't get any file format at all, because you don't get a file: only a File object in memory.
For example: File file = new File("D:/light");
You can produce all the examples you want, but no file is created, and no file format.
In any case Java doesn't care about filename extensions. Your operating system might, but that's a different story.
I have a Java Spring MVC web application. From client, through AngularJS, I am uploading a file and posting it to Controller as webservice.
In my Controller, I am gettinfg it as MultipartFile and I can copy it to local machine.
But I want to upload the file to Amazone S3 bucket. So I have to convert it to java.io.File. Right now what I am doing is, I am copying it to local machine and then uploading to S3 using jets3t.
Here is my way of converting in controller
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile mFile=mRequest.getFile(itr.next());
String fileName=mFile.getOriginalFilename();
fileLoc="/home/mydocs/my-uploads/"+date+"_"+fileName; //date is String form of current date.
Then I am using FIleCopyUtils of SpringFramework
File newFile = new File(fileLoc);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(mFile.getBytes(), newFile);
So it will create a new file in the local machine. That file I am uplaoding in S3
S3Object fileObject = new S3Object(newFile);
s3Service.putObject("myBucket", fileObject);
It creates file in my local system. I don't want to create.
Without creating a file in local system, how to convert a MultipartFIle to java.io.File?
MultipartFile, by default, is already saved on your server as a file when user uploaded it.
From that point - you can do anything you want with this file.
There is a method that moves that temp file to any destination you want.
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/multipart/MultipartFile.html#transferTo(java.io.File)
But MultipartFile is just API, you can implement any other MultipartResolver
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/multipart/MultipartResolver.html
This API accepts input stream and you can do anything you want with it. Default implementation (usually commons-multipart) saves it to temp dir as a file.
But other problem stays here - if S3 API accepts a file as a parameter - you cannot do anything with this - you need a real file. If you want to avoid creating files at all - create you own S3 API.
The question is already more than one year old, so I'm not sure if the jets35 link provided by the OP had the following snippet at that time.
If your data isn't a File or String you can use any input stream as a data source, but you must manually set the Content-Length.
// Create an object containing a greeting string as input stream data.
String greeting = "Hello World!";
S3Object helloWorldObject = new S3Object("HelloWorld2.txt");
ByteArrayInputStream greetingIS = new ByteArrayInputStream(greeting.getBytes());
helloWorldObject.setDataInputStream(greetingIS);
helloWorldObject.setContentLength(
greeting.getBytes(Constants.DEFAULT_ENCODING).length);
helloWorldObject.setContentType("text/plain");
s3Service.putObject(testBucket, helloWorldObject);
It turns out you don't have to create a local file first. As #Boris suggests you can feed the S3Object with the Data Input Stream, Content Type and Content Length you'll get from MultipartFile.getInputStream(), MultipartFile.getContentType() and MultipartFile.getSize() respectively.
Instead of copying it to your local machine, you can just do this and replace the file name with this:
File newFile = new File(multipartFile.getOriginalName());
This way, you don't have to have a local destination create your file
if you are try to use in httpentity check my answer here
https://stackoverflow.com/a/68022695/7532946
The Java.iO.File document says the following words about its constructor which takes the pathname:
public File(String pathname)
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
But what if the pathname points to a file which is already existing?
File file = new File(PATH_TO_AN_EXISTING_FILE);
Does the above file instance represent a fresh new file (with the existing one be deleted?) Or does it represent the existing file ?
What the documentation says is that it will create a new File instance. This mean it will create a new instance in memory of the File class.
This object will point to a file on you file system. However, if the file exists, it will not create a new file.
I think the documentation is a little confusing: creating a new File object in Java does not mean creation of a new file in your file system. The File object is merely an abstract representation of file and directory pathname, it may or may not represent a real file on disk or on a network storage.
It is more or less equivalent to a String representing an address of something: when you write
String str = "1600 Pennsylvania Ave NW, Washington, DC 20500";
you create a string with an address of an existing building. There is no other connection between the string str that you created and The White House that happens to be located at that address.
The only difference between a File created with an existing path name and a file created with a non-existent path name is that the call of exists() on the former will return true, while the same call on the later would return false.
A File is not directly linked to an actual file on the file system. If the file exists, it will point to that file. If the file doesn't exist, it will not create it. exist() will return false.
This is a very confusingly named class.
A File object represents a file path, not an actual file. So when you create a File object you do not change anything on the filing system. Conceptually, it's no different to a String.
In java.nio, the class has been renamed to (the much more intuitive) Path.
The java.io.File class represents a path on some file system. It is not directly bound to a file. You are not opening a file when you create a File instance.
A File object is merely an object on the heap. Yes, it does have fields and methods that imply that this object represents a real file (or a directory: see the ambiguity?).
You can create File objects for files/directories that do not exist: nothing will happen to the file system; the File instances will be created. After all, a File is just a descriptor.
Furthermore, you can create several File objects with different paths (esp. when one is absolute and others are relative from different parent paths), but they will all point to the same file/directory when they are actually evaluated (by opening a file with In/OutputStream, Reader/Writer; when checking with exists() or creating: createFile(), createDirectory().
File f=new File("C://Existing_file")
above line indicates already existed file not the new one to be created file.
File class instance always refers to IO operations and also it always refers to already consisted file
By creating new instance
File f= new File("ABC.txt");
This new object of file will point to a file named ABC.txt in your system, if present. If the ABC.txt file is not there, then the file object simply does not point to any file.
When a file is stored in a computer. The information related to the file is also stored( you can check it in the properties by right clicking on file). These are those information that is about the file.
So the File class object does nothing except represents the information about the file.
The File class object only provides you with information about the file and the same is stated in its definition.
New to Java. I am building a Java HTTP server (no special libraries allowed). There are certain files I need to serve (templates is what I call them) and I was serving them up using this piece of code:
this.getClass().getResourceAsStream("/http/templates/404.html")
And including them in my .jar. This was working. (I realize I was reading them as an input stream.)
Now I want to store all of my files (as File type) for templates, regular files, redirects in a hashmap that looks like this: url -> file. The I have a Response class that serves up the files.
This works for everything except my templates. If I try to insert the getResource code in the hashmap, I get an error in my Response class.
This is my code that I am using to build my hashmap:
new File(this.getClass().getResource("/http/templates/404.html").getFile())
This is the error I'm getting:
Exception in thread "main" java.io.FileNotFoundException: file:/Users/Kelly/Desktop/Java_HTTP_Server/build/jar/server.jar!/http/templates/404.html (No such file or directory)
I ran this command and can see the templates in my jar:
jar tf server.jar
Where is my thinking going wrong? I think I'm missing a piece to the puzzle.
UPDATE: Here's a slice of what I get when I run the last command above...so I think I have the path to the file correctly?
http/server/serverSocket/SystemServerSocket.class
http/server/serverSocket/WebServerSocket.class
http/server/ServerTest.class
http/templates/
http/templates/404.html
http/templates/file_directory.html
http/templates/form.html
The FileNotFoundException error you are getting is not from this line:
new File(this.getClass().getResource("/http/templates/404.html").getFile())
It appears that after you are storing these File objects in hash map, you are trying to read the file (or serve the file by reading using FileInputStream or related APIs). It would have been more useful if you had given the stack trace and the code which is actually throwing this exception.
But the point is that files present within the JAR files are not the same as files on disk. In particular, a File object represents an abstract path name on disk and all standard libraries using File object assume that it is accessible. So /a/path/like/this is a valid abstract path name, but file:/Users/Kelly/Desktop/Java_HTTP_Server/build/jar/server.jar!/http/templates/404.html is not. This is exactly what you get when you call getResource("/http/templates/404.html").getFile(). It just returns a string representing something that doesn't exist as a file on disk.
There are two ways you can serve resources from class path directly:
Directly return the stream as a response to the request. this.getClass().getResourceAsStream() will return you the InputStream object which you can then return to the caller. This will require you to store an InputStream object in your hash map instead of a file. You can have two hash maps one for files from class path and one for files on disk.
Extract all the templates (possibly on first access) to a temporary location say /tmp and then store the File object representing the newly extracted file.
Lets say I've got a file in D: which has a filepath as:
D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01
at the moment the name of this file is not meaningful. It doesn't have a format. I would like to have the ability to create file object from the above filepath in Java and change its name and format before writing it into bytes. The new path could be as following:
D:\work\2012\018\08\mywork.pdf
After the changes have been made, I should still be able to gain access to the original file per normal.
I already know the type of the file and its name so there won't be a problem getting those details.
Just rename the file:
File file = new File(oldFilepath);
boolean success = file.renameTo(new File(newFilepath));
You could also just give a filename and use the same parent as your current file:
File file = new File(oldFilepath);
file.renameTo(new File(file.getParentFile(), newFilename));
It's not really clear what exactly you want; I hope this answer is useful to you.
Suppose you have a java.io.File object that represents D:\work\2012\018\08\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01, and that you want to have a File object that represents D:\work\2012\018\08\mywork.pdf. You already know the new filename mywork.pdf but you want to get the directory name from the original File object. You can do that like this:
File original = new File("D:\\work\\2012\\018\\08\\2b558ad8-4ea4-4cb9-b645-6c9a9919ba01");
// Gets the File object for the directory that contains the file
File dir = original.getParentFile();
// Creates a File object for a file in the same directory with the name "mywork.pdf"
File result = new File(dir, "mywork.pdf");