Please write a java code put the secret file in a text file
Please write a java code
(put the secret file in a text file) the secret file is
Process a text file in order to decode a secret message. We will use the first letter of every 5th token starting with the first word read in from a file to reveal the secret message.
1-Copy the file secret.txt. This file is only one line long. It contains 2 sentences.
2-Write a main method that will read the file secret.txt, separate it into word tokens.
3-You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. These letters should be converted to capitals, then be appended to a StringBuilder object to form a word which will be printed to the console to display the secret message.
Solution
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class RevealSecret {
/*
Format of file should be 2 sentences should be separated by space.
Example:
Sentence1 : Hello Guys.
Sentence2 : Chegg Rocks!.
File Content should be:
Hello Guys. Chegg Rocks!
*/
public static String fileContent(String filepath)
{
Charset UTFcharset = Charset.forName(\"UTF-8\");
Path filePath = Paths.get(filepath);
String fileText = \"\";
try (BufferedReader fileReader = Files.newBufferedReader(filePath, UTFcharset)) {
String line = null;
StringBuilder fileTextBuilder = new StringBuilder();
while ((line = fileReader.readLine()) != null) {
fileTextBuilder.append(line);
}
fileText = fileTextBuilder.toString();
} catch (IOException x) {
System.err.format(\"IOException: %s%n\", x);
}
return fileText;
}
public static void main(String[] args)
{
//Change the fileContent parameter to the actual filepath.Below filepath is for my system.
String fileText = fileContent(\"/Users/deepanshugupta/NetBeansProjects/Chegg/secret.txt\");
System.out.println(\"Content of file is : \ \"+fileText);
String spacesDelim = \" \";
StringTokenizer st = new StringTokenizer(fileText, spacesDelim);
StringBuilder secretBuilder = new StringBuilder();
int iterator = 0;
while (st.hasMoreElements()) {
if(iterator%5==0)
secretBuilder.append(st.nextElement().toString().toUpperCase().charAt(0));
else
st.nextElement();
iterator++;
}
String secret = secretBuilder.toString();
System.out.println(\"Secret is \"+secret);
}
}
OUTPUT:
run:
Content of file is :
January is the first month and December is the last. Violet is a purple color as are lilac and plum.
Secret is JAVA
BUILD SUCCESSFUL (total time: 0 seconds)

