Copy a .text file using a stream in Java?
I want to copy the file "Hello, how are you?" via stream and create a new file called "copy.txt." Why doesn't this work? I get a FileNotFoundException.
Code is attached below:
package de.thws; // Von mir zum testen von Streams import java.io.*; public class PerStreamDateiEinlesen { public static void main(String[] args) throws FileNotFoundException { copyFileWithErrorHandling3Modularized(); } public static void copyFileWithErrorHandling3Modularized() { // try-with-resource statement try (InputStream fis = new FileInputStream("Hallo wie gehts.text"); OutputStream fos = new FileOutputStream("copy.txt");) { copyImproved(fis, fos); } catch (IOException e) { e.printStackTrace(); } } // Hier kopiere ich die Datei static void copyImproved(InputStream is, OutputStream os) throws IOException { byte[] b = new byte[1024]; int n; do { n = is.read(b); //kann maximal 1024 bytes lesen if (n != -1) os.write(b, 0, n); } while (n != -1); } }
On the one hand, the text file is in the wrong place. It must lie where the program is finally executed, so here the folder "Maven".
On the other hand, the file has the ending .txt and not as in your code .text.
OK. Thanks for the hint with .text
"For one, the text file is in the wrong place. It has to lie where the program is finally executed, so here the folder "Maven".
The file is located in Maven/de/thws/lektion17….
So the file is in the folder Maven?
You're right. But that's not like file paths. The file is located in thws folder.
C:\Users\User\IdeaProjects\Maven\src\main\java\de\thws
the path is the file. This is in the folder Maven
So, I've added the Hello file to the Maven folder as you said. Then I ran my code. Now a copy.txt file has been created in the Folder Maven.
In Intellij, I can't see the two files in the project window when I click on the Maven folder.
You're using the file name "Hello like gos.text" instead of "Hello like gos.txt". This will be your fault.
Habs changed: Hello as is possible.txt
Same errors still