Dear expert, The program is run , but output file is blank. i was put my input.t
ID: 3882826 • Letter: D
Question
Dear expert,
The program is run , but output file is blank. i was put my input.txt and output.txt file into package. Can you help me how to get my output into output.txt file please.
import java.io.*; import java.util.*; public class Slang { public static void main(String[] args) { //Input file File inp_f = new File("input.txt"); //Output file File out_f = new File("output.txt"); try { //Scanner object to scan Input file Scanner s = new Scanner(inp_f); try { // PrintWriter object to write to Output file PrintWriter outp = new PrintWriter(out_f); //while there are still words left in the file, iterate!! while(s.hasNext()) { //get the next line String str = s.nextLine(); //For probability 1/2,use Random class Random rand = new Random(); if(rand.nextInt(10)%2==0) { // Apply condition 5 outp.print("Yo!"); } //Split the line by space to get words String[] ss = str.split(" "); int n =ss.length; //Traverse all words in the line till no. of words <=10 for(int i=0;i<10 && i
Explanation / Answer
you can use the below code to read and write into file.
kindly provide the exact location of the file. Else it will fail to read or write
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
public class TextFileReadingExample3 {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("input.txt"); //provide full file path
FileWriter writer = new FileWriter("output.txt", true); //provide full path of file
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) { //each line from file will be stored in line variable.
System.out.println(line);//prints in console
try{
writer.write(line);
writer.write(" ");
}
catch(IOException e){
System.out.println("Error while writing the file");
}
}
reader.close();
} catch (IOException e) {
System.out.println("Error while Reading the file");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.