How do I resolve this error using Paths.of? - java

I have been trying many of the examples provided and have yet to be successful. Here is the code I am currently trying, but getting an error in Eclipse on Paths.of (the of is underlined in red) that says: "rename in file".
String content;
try {
content = Files.readAllLines(Paths.of("C:", "Calcs.txt"));
} catch (IOException e1) {
e1.printStackTrace ();
}
System.out.println (content);

First it is not possible, if you get a list as return type, to assign this to a string. So you must write:
List<String> content;
Second regarding to the Java 8 documentation there is no method of available for this class. You can use the method get like this:
List<String> content = Files.readAllLines(Paths.get("C:", "Calcs.txt"));
Otherwise there exists a method of in the Path class since Java 11. Therefore you can write something like that:
List<String> content = Files.readAllLines(Path.of("C:", "Calcs.txt"));

You're probably looking for Paths.get:
String content;
try {
content = String.join("\n", Files.readAllLines(Paths.get("/home/hassan", "Foo.java")));
} catch (IOException e1) {
e1.printStackTrace ();
}

Related

Why can't I catch the TesseractException?

I am using Tess4j for using Tesseract-OCR technology and I have been using the following code:
During testing I wanted to test the catch close so I was feeding wrong information to Tesseract, which should result in TesseractException.
I managed to induce a TesseractException from the createDocuments() method.
Here is the stack trace:
Note that in the exception we can find doOcr()'s line 125, which is within the try-catch clause, but even though console shows a TesseractException being thrown, the code moves onto line 126 returning true.
I use net.sourceforge.tess4j.Tesseract to initiate the OCR proccess, but I tried net.sourceforge.tess4j.Tesseract1 too, which resulted the same red console output that is done by Tess4j, but no TesseractException.
My question is what am I doing wrong? I am just assuming there is an issue with my code, because TesseractExceptionis being thrown, but my code is not catching it.
Look at the source code of Tesseract.java:
#Override
public void createDocuments(String[] filenames, String[] outputbases, List<RenderedFormat> formats) throws TesseractException {
if (filenames.length != outputbases.length) {
throw new RuntimeException("The two arrays must match in length.");
}
init();
setTessVariables();
try {
for (int i = 0; i < filenames.length; i++) {
File workingTiffFile = null;
try {
String filename = filenames[i];
// if PDF, convert to multi-page TIFF
if (filename.toLowerCase().endsWith(".pdf")) {
workingTiffFile = PdfUtilities.convertPdf2Tiff(new File(filename));
filename = workingTiffFile.getPath();
}
TessResultRenderer renderer = createRenderers(outputbases[i], formats);
createDocuments(filename, renderer);
api.TessDeleteResultRenderer(renderer);
} catch (Exception e) {
// skip the problematic image file
logger.error(e.getMessage(), e);
} finally {
if (workingTiffFile != null && workingTiffFile.exists()) {
workingTiffFile.delete();
}
}
}
} finally {
dispose();
}
}
/**
* Creates documents.
*
* #param filename input file
* #param renderer renderer
* #throws TesseractException
*/
private void createDocuments(String filename, TessResultRenderer renderer) throws TesseractException {
api.TessBaseAPISetInputName(handle, filename); //for reading a UNLV zone file
int result = api.TessBaseAPIProcessPages(handle, filename, null, 0, renderer);
if (result == ITessAPI.FALSE) {
throw new TesseractException("Error during processing page.");
}
}
Exception is thrown at line 579. This method is called by a public method above - at line 551. This is inside the try-catch block with logger.error(e.getMessage(), e); in the catch body (line 555).
Now the question is what you really want to achieve?
If you don't want to see this log, you can configure slf4j to not print the log from this library.
If you want to get the actual exception, it is not possible as the library swallows it. I am not familiar with the library, but looking at the code it doesn't seem like there is any nice option - the method that throws the exception is private and is used only in this one place - under the try-catch block. However, the exception is thrown when api.TessBaseAPIProcessPages(...) returns ITessAPI.FALSE and api has a getter. So you could get it, call TessBaseAPIProcessPages(...) method and check for the result. This might be not ideal as you will probably be processing every image twice. Another solution is to fork the source code and modify it yourself. You might also want to contact the author and ask for advice - you could take it further and submit a pull request for them to approve and release.
Add pdf.ttf file to tessdata path (tessdata/pdf.ttf)
pdf.ttf

Issue with loading csv with ejml

I'm encountering some problems by using the MatrixIO.loadcsv() function in ejml. In fact, I need to load a file into a matrix; i'm following this official example:
public static void main( String args[] ) {
DMatrixRMaj A = new DMatrixRMaj(2,3,true,new double[]{1,2,3,4,5,6});
try {
MatrixIO.saveCSV(A, "matrix_file.csv");
DMatrixRMaj B = MatrixIO.loadCSV("matrix_file.csv");
B.print();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
But when I try my code
DMatrixRMaj B = MatrixIO.loadCSV("sets.csv");
B.print();
I always obtain a FileNotFoundException... but the name of the file is correct and in the same folder of the source code. Where can be the problem?
The solution for me (I'm using Windows 10) is to use absolute path, because it seems not to recognize relative ones on my system, despite of the official examples.

Jsoup is not Correctly Working

Hello guys i have an problem by Jsoup it is not working and i have no idea to figured it out here is the Code
private void getWebsite() {
Document doc = null;
try {
doc = Jsoup.connect("http://www.jean-clermont-schule.de/seite/90384/vertretungsplan.html").get();
Elements newsHeadlines = doc.select("content");
} catch (IOException e) {
e.printStackTrace();
}
}
And here is an Picture
Your code you provided is valid and compiles so the error is likely outside of what you've shown us. Looking at your picture, I guess you've imported the wrong Document class. Check your imports.
I am unable to add comment above.
I think that the code line Elements newsHeadlines = doc.select("content"); is wrong because content isn't tag for this link.
You must provide tag name with attribute and value being optional while using .select("");
You may try Elements newsHeadlines = doc.select("div[id=content]");

Get content of a file inside a directory

I want to get the content of a file inside a directory:
/sys/block/sda/device/model
I use this code to get the content:
String content = new String(Files.readAllBytes(Paths.get("/sys/block/sda/device/model")));
But in some scenarios, I have cases like this:
/sys/block/sda/device/model
/sys/block/sdb/device/model
/sys/block/sdc/device/model
How I can iterate all the directories starting with
sd* and print the file model?
Can you show me some example for Java 8 with filter?
Here is an example of how to do this using Java 8 features:
Function<Path,byte[]> uncheckedRead = p -> {
try { return Files.readAllBytes(p); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
};
try(Stream<Path> s=Files.find(Paths.get("/sys/block"), 1,
(p,a)->p.getName(p.getNameCount()-1).toString().startsWith("sd"))) {
s.map(p->p.resolve("device/model")).map(uncheckedRead).map(String::new)
.forEach(System.out::println);
}
This is an example that strives for compactness and working stand-alone. For real applications, it’s likely that you would do it a bit differently. The task of using an IO operation as a Function which doesn’t allow checked exception is quite common so you might have a wrapper function like:
interface IOFunction<T,R> {
R apply(T in) throws IOException;
}
static <T,R> Function<T,R> wrap(IOFunction<T,R> f) {
return t-> { try { return f.apply(t); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
};
}
Then you can use
try(Stream<Path> s=Files.find(Paths.get("/sys/block"), 1,
(p,a)->p.getName(p.getNameCount()-1).toString().startsWith("sd"))) {
s.map(p->p.resolve("device/model")).map(wrap(Files::readAllBytes))
.map(String::new).forEach(System.out::println);
}
But maybe you’d use newDirectoryStream instead even if the returned DirectoryStream is not a Stream and hence requires a manual Stream creation as this method allows passing a glob pattern like "sd*":
try(DirectoryStream<Path> ds
=Files.newDirectoryStream(Paths.get("/sys/block"), "sd*")) {
StreamSupport.stream(ds.spliterator(), false)
.map(p->p.resolve("device/model")).map(wrap(Files::readAllBytes))
.map(String::new).forEach(System.out::println);
}
Finally, the option to process the files as stream of lines should be mentioned:
try(DirectoryStream<Path> ds
=Files.newDirectoryStream(Paths.get("/sys/block"), "sd*")) {
StreamSupport.stream(ds.spliterator(), false)
.map(p->p.resolve("device/model")).flatMap(wrap(Files::lines))
.forEach(System.out::println);
}
Rather using st* it's better if you can first search the existing folder inside the path /sys/block by using below code.
Please find working example :-
String dirNames[] = new File("E://block").list();
for(String name : dirNames)
{
if (new File("E://block//" + name).isDirectory())
{
if(name.contains("sd")){
String content = new String(Files.readAllBytes(Paths.get("E://block//"+name+"//device//model")));
System.out.println(content);
}
}
}

Serialization and Data Structures

Hi all I need an advice.
I'll explain my problem. I want take data from web , elaborate the result, keep it and serialize on file.
I need to restore and use data from file , somehow. I dont want that file is been overwritten and lose old data.I need have a sort of list of Object in the File where i can search the last , use Method of another class to find some values etc , insert or similar, etc.....
In this case i used ArrayList but i dont know if it was the best choise.
I tried to do this but i have a problem know. In the specific if use a Class called Data and i want a serilizate file that keep ArrayList. So when i call method save(Object obj) of FileStructureClass(a class that i made to save, load file ) in this method i need to check if file already has an ArrayList so if it's true i can add in that Arraylist the Object , passed as parameter , else i return a new ArrayList. Of course i do a cast from Object to Data Class when i add in ArrayList.
I would fix this problem and then after find a better solution (if there is) to my problem.
The Data Class contains only 3 String and 1 GregoriusCalendar. Keep in mind(for the choise as ArrayList as Solution) that i need save file 1 time at day(i do a check with last element of the arraylist and do check with actual GregoriusCalendar..if past 1 day i can insert the element in arraylist).
After Explain the situation i list my problems
When i try to save for the FIRST time a Data Object in the Arraylist i have an error java.io.EOFException , i think that the problem is in tmp= ArrayList)ois.readObject(); but i cant find a solution. Dont happen when i insert manually a DataObject in the ArrayList and i use a method to insert a second one
According to you , ArrayList is a valid solution for my situation?
This method check if the file has data or not.
If it's empty i create a new one ArrayList and return it
otherwise i read the ArrayList already store in the file , and i return it
public ArrayList<Dati> check() {
ArrayList<Dati> tmp = new ArrayList<Dati>();
ObjectInputStream ois;
try{
fileInput = new FileInputStream("prova.dat");
ois = new ObjectInputStream(fileInput);
if (ois.readObject() == null) {
Logger.getLogger("file is empty");
ois.close();
return tmp;
}
//The error that i recive arrives from the under line
// (Impossible load file check method: java.io.EOFException
tmp = (ArrayList<Dati>) ois.readObject();
ois.close();
} catch (IOException e) {
System.out.println("Impossibile caricare i dati metodo check: "+e);
}
catch (ClassNotFoundException e) {
System.err.println("error");
}
return tmp;
}
//This method recive data of file that contains ArrayList<Data>
// and add to this a Data Object gave as Parameter
public void save(Object obj){
try{
ArrayList<Data> temp = check();
temp.add((Data) obj);
ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("prova.dat"));
os.writeObject(temp);
os.flush();
os.close();
}
catch(IOException e){
System.out.println("Impossible save datas: "+e);
}
}
public Object load(String path){
Object obj=null;
try{
fileInput=new FileInputStream(path);
ois=new ObjectInputStream(fileInput);
obj=ois.readObject();
ois.close();
}
catch(IOException e){
System.out.println("Impossible load file: "+e);
}
catch(ClassNotFoundException e){
System.err.println();
}
return obj;
}
When i try to save for the FIRST time a Data Object in the Arraylist
i have an error java.io.EOFException , i think that the problem is
in tmp= (ArrayList)ois.readObject(); but i cant find a solution. Dont
happen when i insert manually a DataObject in the ArrayList and i
use a method to insert a second one
This seems to be correct. Looking at javadoc, it does seem like ois.readObject() returns null when there is nothing in the file. One approach I can think of is to initialize the file with an empty ArrayList in setup phase.
According to you , ArrayList is a valid solution for my situation?
I don't see why not. But it depends on what you will do with the list after reading it. If you have to search it often and it is large then you may consider a different data structure.

Categories