9.1k views
5 votes
Write 5-6 lines of code to open a PrintWriter and write out the contents of the plants array into a text file named plants.txt

User Anish K
by
7.6k points

1 Answer

7 votes

Here's an example of how you might open a PrintWriter and write out the contents of the plants array into a text file named plants.txt in Java:

String[] plants = {"Rose", "Tulip", "Lily", "Sunflower"};

PrintWriter writer = new PrintWriter("plants.txt", "UTF-8");

for (String plant : plants) {

writer.println(plant);

}

writer.close();

Here's an example of how you might open a PrintWriter and write out the contents of the plants array into a text file named plants.txt in Python:

plants = ["Rose", "Tulip", "Lily", "Sunflower"]

with open("plants.txt", "w") as file:

for plant in plants:

file.write(plant + "\\")

Please note that in Python, the "w" mode of the open function will truncate the file if it already exists and create a new one if it does not.

You can also use the append mode to add the new data to the existing file.

with open("plants.txt", "a") as file:

for plant in plants:

file.write(plant + "\\")

You can also use the writelines method to write out the contents of the plants array into the text file.

with open("plants.txt", "w") as file:

file.writelines("\\".join(plants))

Please note that the above code examples will create the text file in the same directory where the code is running. If you want to save the file in a specific directory, you will have to provide the full path of the directory in the filename.

User EmerG
by
8.4k points