- Java: Transfer local file to output stream of server
- Java: Transfer local file to output stream of server
- How to know where FileOutputStream will write file?
- How to write to a local file in a Java Dynamic WebService application?
- Saved searches
- Use saved searches to filter your results more quickly
- projectyotta/Socket_FileServer
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
Java: Transfer local file to output stream of server
The code is something as follows: How can I send the data of the file in the stream to the server? Solution: FileOutputStream is used to write files, and it seems like you need to Read file, then you should use FileInputStream. Read file content to byte array Convert InputStream to byte array in Java Question: I have instance and I want to write file. after execution my code I can’t find file on my filesystem.
Java: Transfer local file to output stream of server
I have a fileoutputstream and am trying to get the contents of this file on a remote server. The server has an API to which I should POST the contents of the file (which is an .xls file). The API requires me to POST the data to its API URL and set the ContentType to that of an .xls file in this case.
The code is something as follows:
try < outputFile = new FileOutputStream("myfile.xls"); >catch (FileNotFoundException e) < e.printStackTrace(System.err); >handle.sendRequest("https://server/API/file/id", "POST", "application/vnd.ms-excel", data);
How can I send the data of the file in the stream to the server?
FileOutputStream is used to write files, and it seems like you need to Read file, then you should use FileInputStream. Read file content to byte array Convert InputStream to byte array in Java
try (InputStream is = new FileInputStream("myfile.xls")) < ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] dataPart = new byte[16384]; while ((nRead = is.read(dataPart, 0, dataPart.length)) != -1) < buffer.write(dataPart, 0, nRead); >buffer.flush(); byte[] data = buffer.toByteArray(); handle.sendRequest("https://server/API/file/id", "POST", "application/vnd.ms-excel", data); >
Java — Create a File, In this case, a new file is created when we instantiate the FileOutputStream object. If a file with a given name already exists, it will be
How to know where FileOutputStream will write file?
I have instance FileOutputStream and I want to write file.
after execution my code I can’t find file on my filesystem.
maybe FileOutputStream have method that I will know where it writes?
You decide where the file will be located, when you call constructor.
new FileOutputStream("path/to/my/file.txt");
There are a few similiar constructors. You can pass for example File or FileDescriptor parameter too. Just read Java API Doc.
When you created the FileOutputStream instance, you would have given either File object or a String path (absolute path with file name) or a FileDescriptor object. That path is where your file would be placed.
Have a look at the various constructors of FileOutputStream and check which was the one you had used.
FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified File object. FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object. FileOutputStream(FileDescriptor fdObj) Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. FileOutputStream(String name) Creates a file output stream to write to the file with the specified name. FileOutputStream(String name, boolean append) Creates a file output stream to write to the file with the specified name.
All overloaded constructors take filename. if file does not exist in the absolute path provided a new one is created. If no absolute path is provided then file will be crated in current directory.
I just started working with Java on a RESTful service project. I have written to a file with FileOutputStream and couldn’t find the file. My OS is Windows, and I am working with Eclipse. I finally found the file where the «eclipse.exe» is located on my computer. It looks like the Java class stored the file there if I did not provide an absolute path. It could be different in your case. This is such an old post but felt like replying as I see some posts asking similar questions even now.
Why is my FileOutputStream saving files in wrong location?, You’re constructing an output stream, then take its string presentation and somehow assume it is a valid path.
How to write to a local file in a Java Dynamic WebService application?
I have a file that contains json data Books.json . The file is located in package com.ebook.database . I can successfully read the file’s contents, but I when I try to write to the file, I get a FileNotFoundException .
Below is my project’s strudture, showing the package in which the Books.json file is located:
Below is the code I use to successfully read the file’s contents ( filePath receives a String value of /com/ebook/database/Books.json and reads the file just fine:
/** * A utility method for reading the data stored in a json file. * * @param filePath path to the desired database table * @return the contents of the desired table * @throws IOException occurs when the desired file is not found */ public static String readFile(String filePath) throws IOException
Below is the code I’m using to try to access the same Books.json file for writing, unsuccessfully:
/** * Adds a new Book to the Books.json file * */ public void postBook(Book book, String filePath) < //create Gson instance with pretty-print Gson gson = new GsonBuilder().setPrettyPrinting().create(); //First, convert the Product object into a Json string try < File file = new File(filePath); OutputStream out = new FileOutputStream(file); /* This logic will check whether the file * exists or not. If the file is not found * at the specified location it would create * a new file*/ if (!file.exists()) < file.createNewFile(); >List books; String updatedBooksJson; //if file is empty, just throw the object in -- no prior comma needed. if(DBHelper.tableIsEmpty(filePath)) < books = new ArrayList(); books.add(book); updatedBooksJson = gson.toJson(books); //writing to the file. byte[] bytes = updatedBooksJson.getBytes(); out.write(bytes[6]); out.flush(); > else < //The file is not empty. Read the list of Products currently //in the file, convert to List, add the new Product, and //update the file books = getAllBooks(filePath); //add the new product to the existing list of products: books.add(book); //write the updated products list to the Products.json file updatedBooksJson = gson.toJson(books); //clear the old file contents FileChannel.open(Paths.get(filePath), StandardOpenOption.WRITE).truncate(0).close(); //write the new file contents //writing to the file. byte[] bytes = updatedBooksJson.getBytes(); out.write(bytes[6]); out.flush(); > out.close(); > catch (IOException e) < e.printStackTrace(); >>
Below is the resulting stacktrace when attempting to write to the /com/ebook/database/Books.json file:
INFO: Server startup in 2782 ms java.io.FileNotFoundException: \com\ebook\database\Books.json (The system cannot find the path specified) at java.base/java.io.FileOutputStream.open0(Native Method) at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292) at java.base/java.io.FileOutputStream.(FileOutputStream.java:235) at java.base/java.io.FileOutputStream.(FileOutputStream.java:185) at com.ebook.dal.BookDAO.postBook(BookDAO.java:59) at com.ebook.services.BookService.addNewBook(BookService.java:38) at com.ebook.resources.BookResource.postNewBook(BookResource.java:72) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:219) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244) at org.glassfish.jersey.internal.Errors.process(Errors.java:292) at org.glassfish.jersey.internal.Errors.process(Errors.java:274) at org.glassfish.jersey.internal.Errors.process(Errors.java:244) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:392) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:317) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:835) Oct 11, 2020 3:32:40 PM org.apache.catalina.core.StandardContext reload
You are mixing classpath and local file system paths here. You should never try to overwrite elements in the classpath like that without knowing what you’re doing as that would potentially charge the behavior of the app when you restart it. Just put the somewhere on the file system and consistently read and write there.
Download a File From an URL in Java, 6 days ago · FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME); FileChannel fileChannel = fileOutputStream.getChannel();. We’ll use the
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
File server using JAVA Sockets
projectyotta/Socket_FileServer
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
FileServer using JavaSocket
This is the program for file server developed using Java Sockets.
To start the server, run the following command —
java -cp pa1.jar server start
To run the client, first youe need to set the enviornment variable named PA1_SERVER=
Following are the different commands supported by the client.
java -cp pa1.jar client upload
java -cp pa1.jar client download
java -cp pa1.jar client dir
java -cp pa1.jar client mkdir
java -cp pa1.jar client rmdir
java -cp pa1.jar client shutdown
Multiple clients can talk to the server at the same time.