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); } }
1 vote, average: 1.00 out of 1 (1 rating, 1 votes, rated)
You need to be a registered member to rate this.
Loading...
Subscribe
Notify of
8 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Robin42
1 year ago
  1. Incorrect file extension (you use .text here while the file ends with .txt.
  2. Try to rename the file so that it does not contain spaces. It may be that you would have to escape the spaces using \ for the file name.
Lezurex
1 year ago

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.

Lezurex
1 year ago
Reply to  RedDevil1982

You're right. But that's not like file paths. The file is located in thws folder.

iSc0field
1 year ago

You're using the file name "Hello like gos.text" instead of "Hello like gos.txt". This will be your fault.