klasscho

Untitled

Mar 3rd, 2020
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. package com.company;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.Scanner;
  7.  
  8. public class Main {
  9.     public static String[] readFromFile() throws IOException {
  10.         Scanner in = new Scanner(System.in);
  11.         String inputFileName;
  12.         System.out.println("Enter a file name: ");
  13.         inputFileName = in.nextLine();
  14.         inputFileName = inputFileName + ".txt";
  15.         FileInputStream inFile = new FileInputStream(inputFileName);
  16.         byte[] line = new byte[inFile.available()];
  17.         inFile.read(line);
  18.         String text = new String(line);
  19.         String[] words = text.split(" ");
  20.         return words;
  21.     }
  22.  
  23.     public static void largestWord_s(String[] words) {
  24.         String[] mas_words = words.split(" ");
  25.         String max = mas_words[0];
  26.         for (int i = 1; i < mas_words.length; ++i) {
  27.             if (max.length() < mas_words[i].length()) {
  28.                 max = mas_words[i];
  29.             }
  30.         }
  31.         System.out.println("The longest word is :" + max);
  32.     }
  33.  
  34.     public static void writeToFile(String largestWord) throws IOException {
  35.         Scanner in = new Scanner(System.in);
  36.         int i;
  37.         String newFileName;
  38.         System.out.println("Enter file name for save:");
  39.         newFileName = in.nextLine();
  40.         newFileName = newFileName + ".txt";
  41.         FileWriter fileWriter = new FileWriter(new File(newFileName));
  42.         fileWriter.write("The longest word is:" + largestWord);
  43.         fileWriter.flush();
  44.     }
  45.  
  46.     public static void main(String[] args) throws IOException {
  47.         String[] words = new String[0];
  48.         words = readFromFile();
  49.         System.out.println(words);
  50.         String longWord = largestWord_s(words);
  51.         writeToFile(longWord);
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment