How to use Apache Commons IO with Java - java

I have a question about Apache Commons IO with Java.
The excercice is to read a text file without using Commons IO, and then using it.
For the first one, my code is this, and this works:
import java.util.Scanner;
public class ReadBook {
private Scanner line;
public void openFile(){
try{
line= new Scanner(new File("books.txt"));
}
catch(Exception e){
System.out.println("File not found");
}
}
public void readFile() {
while (line.hasNext()) {
String book = line.next();
System.out.println(book);
}
}
public void closeFile(){
line.close();
}
}
and the main class:
public class mainClass {
public static void main(String[] args){
ReadBook book = new ReadBook();
book.openFile();
book.readFile();
book.closeFile();
}
}
The teacher gave us this class, and now we are supposed to do the same thing with the Apache Commons IO library.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class Utf8File {
public static String loadFileIntoString(String filePath) throws FileNotFoundException, IOException {
return IOUtils.toString(new FileInputStream(filePath), "UTF-8");
}
public static void saveStringIntoFile(String filePath, String content) throws IOException {
File f = new File(filePath);
FileUtils.writeStringToFile(f, content, "UTF-8");
}
}
I was wondering, do you know how to do it?
Last time I programmed with Java was one year ago hahaha so it is a little bit far away in my memory :O
This is the first homework to do (today was the first class).
I hope someone can help me :)
Thanks!

Related

If i parse an encrypted html file to a string can i somehow obtain the text from it?

import java.net.*;
import java.io.*;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class UrlReaderTest {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.amazon.com/");
String s = null;
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
System.err.println("Error");
}
s = contentBuilder.toString();
Document document = Jsoup.parse(s);
System.out.println(document.text());
}
}
What i am getting has mainly symbols like these: Η1?0 Π??0ή=tθ Jr?/β#Q? l?r{ΪεI/ ΉΟ~νJ?j?Ά-??ΙiLs?YdHλ²ύ?α?η?ογV"ηw[:?0??νSQψyθ?*²?γpI? ??²ρνl???2JμΚ?ΣS?Αl4ςRΛ\KR545υ?SK
Is there anything i can do to transform that in a form that i can use?
I can't find something specific online.
Edit: What i want specificly is to decrypt that information. What i want for example is to be able to take the text from an event page from facebook search it to find the keywords i want and use those somewhere else.
As #t.m.adam noted in his comment, the problem is that the response from stream is gzipped (compressed). So, if you want to read it from the URL stream, you need to pass it through a GZIPInputStream before InputStreamReader (see this answer). Alternatively, as #t.m.adam suggests, you can use Jsoup's built-in connect() method:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class UrlReaderTest {
public static void main(String[] args) {
System.out.println(System.getProperty("java.classpath"));
try {
Document doc = Jsoup.connect("https://www.amazon.com").get();
System.out.print(doc.text());
}
catch (IOException e) {
System.err.println("Error");
}
}
}

Reset the file pointer back to starting position

Is there any way I can reuse the Scanner object to read the same file again.
There is RandomAccessFile class that provides random access (seek) but I am looking for some code that uses Scanner. I know how to go to the stating position of the file by creating a new Scanner object, but the code looks messy.
Is there a neat and short method to do the same.
Thanks in advance:-)
Also could you suggest good source/tutorial for learning file handling :p
Here is what I am trying to do:
Container.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
public class Container {
private Scanner sc;
private Formatter f;
void openFile() throws FileNotFoundException{
sc=new Scanner(new File("source"));
}
void readData(){
while(sc.hasNext()){
System.out.println(sc.next());
}
}
void readlineData(){
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
void closeFile(){
sc.close();
}
void addData() throws FileNotFoundException{
f=new Formatter("source");
f.format("%s%s", "hi "," hello");
}
}
Client.java
import java.io.FileNotFoundException;
public class Client {
public static void main(String[] args) throws FileNotFoundException {
Container c=new Container();
try {
c.openFile();
} catch (FileNotFoundException e) {
System.out.println("No file with this name");
}
//reading word by word
c.readData();//there is content already in the file
//reading line by line
c.readlineData();
//changing the content of the file
c.addData();
//reading the file again
c.readData();
//closing the file
c.closeFile();
}
}
Here i have made a client and a container class.
In the container class i have methods to create a file,read file word by word ,read line by liine and close file.
In the client class i have called these methods .

Comparing Phrases to whole text

I have two text files. The first user inputs a paragraph of text. The second is a dictionary of terms gotten from an owl file. Like so:
Inferior salivatory nucleus
Retrosplenial area
lateral agranular part
I have coded the bits to make these files. I am stuck as to compare the files so that any whole phrases that appear in the dictionary and the paragraph of text are printed out in the command line in Java.
Try following code, it will help you. Correct your file path in fileName and enter your search condition into the while loop:
public class JavaReadFile {
public static void main(String[] args) throws IOException {
String fileName = "filePath.txt";
//read using BufferedReader, to read line by line
readUsingBufferedReader(fileName);
}
private static void readUsingBufferedReader(String fileName) throws IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
//process the line
System.out.println(line);
}
//close resources
br.close();
fr.close();
}
}
You could write the file to a string and iterate over the keys in your dictionary and check if they are present in the paragraph with contains. This probably isn't a particularly efficient solution, but it should work.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
String fileString = new String(Files.readAllBytes(Paths.get("dictionary.txt")),StandardCharsets.UTF_8);
Set<String> set = new HashSet<String>();
set.add("ZYMURGIES");
for (String term : set) {
if(fileString.contains(term)) {
System.out.println(term);
}
}
}
}
Here's a Java 8 version of the contains checking.
package insert.name.here;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class InsertNameHere {
public static void main(String[] args) throws IOException {
String paragraph = new String(Files.readAllBytes(Paths.get("<paragraph file path>")));
Files.lines(Paths.get("<dictionary file path>"))
.filter(paragraph::contains)
.forEach(phrase -> System.out.printf("Paragraph contains %s", phrase));
}
}

Unable to write to a file

I have gone through all the related posts in this forum and also googled but not found the exact answer.
When running the below code, I get following error:
The constructor BufferedWriter(FileWriter) is undefined
The constructor FileWriter(String) is undefined
public class FileWriter {
public static void main(String[] args) {
BufferedWriter f = null;
try
{
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
f.close();
}
}
}
I guess you want to use java.io.FileWriter class of java but you redefine it. You can rename your class to something else more meaningful.
You have to import your used classes like BufferedWriter. That's why you get your undefined errors.
Also it is a good practice to check if the writer f is null before closing:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
BufferedWriter f = null;
try {
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e) {
System.out.println(e);
}
finally {
if (f != null)
f.close();
}
}
}
Your class is called FileWriter which conflicts with the name of the java.io.FileWriter. Rename your class something else and then explicitly import the java.io.FileWriter and java.io.BufferedWriter classes.
import java.io.FileWriter;
import java.io.BufferedWriter;
I would also suggest using a more modern idiom: try-with-resources, which automatically closes the writer for you. It's terser and cleaner.
public class Example {
public static void main(String... args) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\A.txt")) {
writer.write("Hello World");
}
}
}
use these steps. This is the correct and easy way to use buffered writer.
1.create File object.
File f = new File(C://A.txt);
create file writer object.
FileWriter fr = new FileWriter(f);
create Buffered writer .
BufferedWriter bw = new BufferedWriter(fr);
4.then you can easily write to the file like below.
bw.write("Hello World");
hope this will be help to you
remember to import
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
those packages will be automatically suggest if you are using ide like netbeans.

Write To file with getResource

I use This methods to Write to a text file(use getResource()... to use in JAR file).
My files are in Classpath,
Here is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class JarWrite {
public JarWrite(){
writethis();
}
public void writethis(){
try{
InputStreamReader isReader= new InputStreamReader(this.getClass().getResourceAsStream("AllBookRecords.txt"));
BufferedReader br = new BufferedReader(isReader);
PrintWriter writer1=new PrintWriter(new File(this.getClass().getResource("Boutput.txt").getPath()));
String Bs;
while( (Bs=br.readLine()) != null ){
writer1.println(Bs);
}
writer1.close();
br.close();
} catch(FileNotFoundException fnfe){
} catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String[] args){
new JarWrite();
}
}
You can't modify resources from CLASSPATH. They are read only. Period.
See also: Java OutputStream equivalent to getClass().getClassLoader().getResourceAsStream().
Try changing:
public void writethis
to
public static void writethis

Categories

Resources