Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Class Work: 1- Create a text file and Read in Java 2- Read a url and show in jav

ID: 3723465 • Letter: C

Question

Class Work: 1- Create a text file and Read in Java 2- Read a url and show in java 3- Read With JSoup and Show in java 4- Read with Jswing to prompt for open file. Show file content in Jpane Java swing example import javax.swing.*; public class InputDemo public static void main(String args[]) String stri JOptionPane.showInputDialog("Enter First Number"); String str2 JOptionPane.showinputDialog("Enter Second Number"); // input dialog returns always a string double fn Double.parseDouble(str1); double sn Double.parseDouble(str2); JOptionPane.showMessageDialog( null, "The Product is " + fn*sn, "Product JOptionPane

Explanation / Answer

Below I Have written codes and snippets for all the problem given

Hope this Helps ....Thank you. :)

1.create a text file and read in java

-->below function line can be used to read text file in java

//please change the path

-->below function line can be used to create text file in java

//new file is created in the directory of where your java file is saved

note:dont forget to import java.io.*;

2.Read URL and show in java

import java.net.*;
import java.io.*;

public class UrlReader
{
public static void main(String[] args) throws Exception
{
    String urlString = "http://localhost:8080/";
  
    // create the url
    URL url = new URL(urlString);
  
    // open the url stream, wrap it an a few "readers"
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

    // write the output to stdout
    String line;
    while ((line = reader.readLine()) != null)
    {
      System.out.println(line);
    }

    // close our reader
    reader.close();
}
}

//note: write your url in place of localhost

3.Read with JSoup and show it in java

//below code is useful in list links from URL

package org.jsoup.examples;

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
* Example program to list links from a URL.
*/
public class ListLinks {
    public static void main(String[] args) throws IOException {
        Validate.isTrue(args.length == 1, "usage: supply url to fetch");
        String url = args[0];
        print("Fetching %s...", url);

        Document doc = Jsoup.connect(url).get();
        Elements links = doc.select("a[href]");
        Elements media = doc.select("[src]");
        Elements imports = doc.select("link[href]");

        print(" Media: (%d)", media.size());
        for (Element src : media) {
            if (src.tagName().equals("img"))
                print(" * %s: <%s> %sx%s (%s)",
                        src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                        trim(src.attr("alt"), 20));
            else
                print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
        }

        print(" Imports: (%d)", imports.size());
        for (Element link : imports) {
            print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
        }

        print(" Links: (%d)", links.size());
        for (Element link : links) {
            print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35));
        }
    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width)
            return s.substring(0, width-1) + ".";
        else
            return s;
    }
}

4.Read with JSwing to open for a new file and show it in JPanel

//below code prompts to select a file in file chooser and it appears in a jpanel

import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

public class FileChooserExample {
    public static void main(String[] args) {
        new FileChooserExample();
    }
    public FileChooserExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
    public class TestPane extends JPanel {
        private JButton open;
        private JTextArea textArea;
        private JFileChooser chooser;
        public TestPane() {
            setLayout(new BorderLayout());
            open = new JButton("Open");
            textArea = new JTextArea(20, 40);
            add(new JScrollPane(textArea));
            add(open, BorderLayout.SOUTH);
            open.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (chooser == null) {
                        chooser = new JFileChooser();
                        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        chooser.setAcceptAllFileFilterUsed(false);
                        chooser.addChoosableFileFilter(new FileFilter() {
                            @Override
                            public boolean accept(File f) {
                                return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
                            }
                            @Override
                            public String getDescription() {
                                return "Text Files (*.txt)";
                            }
                        });
                    }
                    switch (chooser.showOpenDialog(TestPane.this)) {
                        case JFileChooser.APPROVE_OPTION:
                            try (BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile()))) {
                                textArea.setText(null);
                                String text = null;
                                while ((text = br.readLine()) != null) {
                                    textArea.append(text);
                                    textArea.append(" ");
                                }
                                textArea.setCaretPosition(0);
                            } catch (IOException exp) {
                                exp.printStackTrace();
                                JOptionPane.showMessageDialog(TestPane.this, "Failed to read file", "Error", JOptionPane.ERROR_MESSAGE);
                            }
                            break;
                    }
                }
            });
        }
    }
}