Cannot find symbol even with class imported - java

I have a bit of a weird situation.
The problem is with import java.nio.*; and import java.nio.file.Paths;.
First of all, import java.nio.*; should import the second class anyway, but I'm experiencing something weird. It might be a known mistake I'm making but I'm new to Java.
If I import both, or if I import only java.nio.*, I get error: cannot find symbol for Files.write(...). However, if I import only java.nio.file.Paths, I get the same error but for Paths.get(...).
Any idea as to why this is happening? I'm open to exploring other options than these two classes, all I want to do is append a text file.
public static void addAction(String cmd) {
String text = "Text to save to file";
Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}
is the bit where the problem is, but in case it's a problem with something else that I wrote I've attached the whole file below:
import java.io.File; // Find Files
import java.awt.FileDialog; // File Picker
import javax.swing.JFrame; // JFrame
import java.nio.*;
// import java.nio.file.Paths;
class Files {
public static void getApps(final File folder) {
for (final File file : folder.listFiles()) {
String fileName = file.getName();
// System.out.println(fileName);
// System.out.println(file.getPath());
final File subfolder = new File(file.getPath()+"/Contents/Resources");
if (subfolder.exists()) {
String icon = pickFile(subfolder.getPath());
if (icon == null) return;
System.out.println("App Name: " + fileName);
System.out.println("Icon Name: " + icon);
} else {
System.out.println("Directory not found...");
}
}
}
public static String pickFile(String path) {
FileDialog dialog = new FileDialog(new JFrame(), "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setFilenameFilter((File dir, String name) -> name.endsWith(".icns"));
dialog.setDirectory(path);
dialog.setVisible(true);
String fileChosen = dialog.getFile();
return fileChosen;
}
public static void addAction(String cmd) {
String text = "Text to save to file";
Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}
public static void main (String[] args) {
String action = "{\n\"BTTTouchBarButtonName\":\"Messages\",\n\"BTTTriggerType\":629,\n\"BTTTriggerClass\":\"BTTTriggerTypeTouchBar\",\n\"BTTPredefinedActionType\":49,\n\"BTTPredefinedActionName\":\"Launch Application \\/ Open File \\/ Start Apple Script …\",\n\"BTTLaunchPath\":\"file:\\/\\/\\/Applications\\/Messages.app\",\n\"BTTEnabled2\":1,\n\"BTTUUID\":\"F3089B96-FDEF-4D54-9DA8-9CCD3C7AF8A9\",\n\"BTTEnabled\":1,\n\"BTTRequiredModifierKeys\":1048576,\n\"BTTOrder\":1,\n \"BTTIconData\":\"icondata\",\n\"BTTTriggerConfig\":{\n\"BTTTouchBarItemIconHeight\":22,\n\"BTTTouchBarItemIconWidth\":22,\n\"BTTTouchBarItemPadding\":0,\n\"BTTTouchBarFreeSpaceAfterButton\":\"5.000000\",\n\"BTTTouchBarButtonColor\":\"75.323769, 75.323769, 75.323769, 255.000000\",\n\"BTTTouchBarAlwaysShowButton\":\"1\",\n\"BTTTouchBarAlternateBackgroundColor\":\"0.000000, 0.000000, 0.000000, 0.000000\"\n}\n}";
File f = new File("/Users/Andrew/Desktop/testfile.txt");
try {f.createNewFile();}catch(Exception e){}
addAction("open 'btt://add_new_trigger/?json="+action+"'");
}
}
Edit: I am using JDK Version 8-171 for Mac

Java compiler is getting confused because Files is the name of your class so it is looking for a write method in your class. Try leaving only this import :
import java.nio.file.Paths;
And then call the complete class name for java.nio.file.Files:
java.nio.file.Files.write(Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
But then you should handle your IOException also. Add your import and try/catch. Here is your class with no compilation errors:
import java.io.File; // Find Files
import java.io.IOException;
import java.awt.FileDialog; // File Picker
import javax.swing.JFrame; // JFrame
import java.nio.file.Paths;
class Files {
public static void getApps(final File folder) {
for (final File file : folder.listFiles()) {
String fileName = file.getName();
// System.out.println(fileName);
// System.out.println(file.getPath());
final File subfolder = new File(file.getPath()+"/Contents/Resources");
if (subfolder.exists()) {
String icon = pickFile(subfolder.getPath());
if (icon == null) return;
System.out.println("App Name: " + fileName);
System.out.println("Icon Name: " + icon);
} else {
System.out.println("Directory not found...");
}
}
}
public static String pickFile(String path) {
FileDialog dialog = new FileDialog(new JFrame(), "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setFilenameFilter((File dir, String name) -> name.endsWith(".icns"));
dialog.setDirectory(path);
dialog.setVisible(true);
String fileChosen = dialog.getFile();
return fileChosen;
}
public static void addAction(String cmd) {
String text = "Text to save to file";
try{
java.nio.file.Files.write( Paths.get("/Users/Andrew/Desktop/testfile.txt"), text.getBytes());
}catch(IOException e){
System.err.print("Handle your error!");
}
}
public static void main (String[] args) {
String action = "{\n\"BTTTouchBarButtonName\":\"Messages\",\n\"BTTTriggerType\":629,\n\"BTTTriggerClass\":\"BTTTriggerTypeTouchBar\",\n\"BTTPredefinedActionType\":49,\n\"BTTPredefinedActionName\":\"Launch Application \\/ Open File \\/ Start Apple Script …\",\n\"BTTLaunchPath\":\"file:\\/\\/\\/Applications\\/Messages.app\",\n\"BTTEnabled2\":1,\n\"BTTUUID\":\"F3089B96-FDEF-4D54-9DA8-9CCD3C7AF8A9\",\n\"BTTEnabled\":1,\n\"BTTRequiredModifierKeys\":1048576,\n\"BTTOrder\":1,\n \"BTTIconData\":\"icondata\",\n\"BTTTriggerConfig\":{\n\"BTTTouchBarItemIconHeight\":22,\n\"BTTTouchBarItemIconWidth\":22,\n\"BTTTouchBarItemPadding\":0,\n\"BTTTouchBarFreeSpaceAfterButton\":\"5.000000\",\n\"BTTTouchBarButtonColor\":\"75.323769, 75.323769, 75.323769, 255.000000\",\n\"BTTTouchBarAlwaysShowButton\":\"1\",\n\"BTTTouchBarAlternateBackgroundColor\":\"0.000000, 0.000000, 0.000000, 0.000000\"\n}\n}";
File f = new File("/Users/Andrew/Desktop/testfile.txt");
try {f.createNewFile();}catch(Exception e){}
addAction("open 'btt://add_new_trigger/?json="+action+"'");
}
}

In my case it was a JAVA project and the class was written in Kotlin (copy-paste), so I added Kotlin dependencies and the problem is solved.

Related

How to access many resource images in a folder in a jar in Java?

I have got this class for loading blue images, which works fine in Eclipse but not in the exported jar. How can I access all the blue images in the folder (directory) called "blue" without knowing the names of the images?
public class Blue
{
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
List<BufferedImage> blueImagesList = new ArrayList<>();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
UPDATE
I have tried this, but it does not work either. I am getting a NullPointer exception. I tried "/blue" and "blue" and even ".blue".
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import vokabeltrainer.ApplicationImages;
public class Blue
{
public static void read() throws Exception
{
List<BufferedImage> blueImagesList = new ArrayList<>();
try (Stream<Path> pathStream = Files.walk(Paths.get(Blue.class
.getClassLoader().getResource("blue").toURI().toURL().getPath()))
.filter(Files::isRegularFile))
{
for (Path file : (Iterable<Path>) pathStream::iterator)
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream(file.toString())));
;
}
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
I adapted an answer from How to list the files inside a JAR file?
First I distinguish wether I am running from jar or Eclipse:
try
{
Blue.readZip(); // when inside jar
}
catch (Exception e)
{
try
{
Blue.read(); // during development
}
catch (Exception e1)
{
System.out.println("Could not read blue.");
e1.printStackTrace();
}
}
Then class Blue looks like this:
public class Blue
{
private static List<BufferedImage> blueImagesList = new ArrayList<>();
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
public static void readZip() throws Exception
{
CodeSource src = Blue.class.getProtectionDomain().getCodeSource();
if (src != null)
{
URL jar = src.getLocation();
ZipFile zipFile = new ZipFile(jar.getFile());
ZipInputStream zip = new ZipInputStream(jar.openStream());
while (true)
{
ZipEntry ze = zip.getNextEntry();
if (ze == null)
break;
String name = ze.getName();
if (name.startsWith("vokabeltrainer/resources/blue/"))
{
blueImagesList.add(ImageIO.read(zipFile.getInputStream(ze)));
}
}
}
else
{
throw new IOException("can not find code source for blue images");
}
ApplicationImages.setBlueImages(blueImagesList);
}
}

Is there a standard way to transform a String into a File considerning the possibility of a URL/URI formatted input String

I would like to obtain the most accurate File typed representation of a String that is supposed to refer to a local (existing) file in one of several forms like:
String file0 = "/home/my_user/file.txt"
String file1 = "file:///home/my_user/file.txt"
String file2 = "file.txt"; // assuming that the working dir is /home/my_user.
Is there a (quasy) single liner using the standard library or perhaps a common third party like apache-commons that would do the trick?
Thanks.
You can define your own function for this purpose. Given below is the function definition and test code:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
File file = null;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException e) {
return new File(pathOrUri);
} catch (URISyntaxException e) {
return new File(pathOrUri);
}
if (uri != null) {
file = new File(uri);
}
return file;
}
}
Output:
true
true
true
[Update]
Given below is a more simplified version:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String file0 = "/Users/arvind.avinash/file.txt";
String file1 = "file:///Users/arvind.avinash/file.txt";
String file2 = "file.txt"; // assuming that the working dir is /Users/arvind.avinash.
System.out.println(getFile(file0).exists());
System.out.println(getFile(file1).exists());
System.out.println(getFile(file2).exists());
}
static File getFile(String pathOrUri) {
URI uri;
try {
uri = new URL(pathOrUri).toURI();
} catch (MalformedURLException | URISyntaxException e) {
return new File(pathOrUri);
}
return new File(uri);
}
}
You be able to call new File(x) on examples 1 and 3 and it should work.
As for #2, you can create a URI, and then create File from that. In fact I think they all probably will work using URI
String fileStr = "file:///home/my_user/file.txt";
try {
URI uri = new URI(fileStr);
File f = new File(uri);
} catch (URISyntaxException ex) { ...}

Message console on JFrame does not work by double click on jar

So I created a message console. And used append to display messages and it works perfectly by running java -jar JavaProgram, however when I double click on it the application runs and I see the JFrame but nothing is displayed. The text that I did append is not present.
By the way, double clicking it on windows does display the message output but on my linux system nothing is displayed.
I'm running the same version of java on each machine.
Code Below:
package pdfCounter;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static JTextArea textComponent;
public static int count;
public static void main(String args[]) {
try {
JFrame somePanel = new JFrame();
somePanel.add(new JLabel(" Message Console"), BorderLayout.NORTH);
textComponent = new JTextArea(5, 10);
somePanel.setVisible(true);
somePanel.setSize(900, 300);
somePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
somePanel.add(new JScrollPane(textComponent));
pdfCounter.MessageConsole mc = new pdfCounter.MessageConsole(textComponent);
mc.redirectOut(null, System.out);
mc.redirectErr(Color.RED, null);
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
File root = new File(s);
count = 0;
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext(); ) {
try {
File file = (File) iterator.next();
if (file.getName().endsWith(".pdf")) {
String absoluteFile = file.getAbsolutePath();
append(absoluteFile);
PDDocument doc = PDDocument.load(new File(file.getAbsolutePath()));
count = doc.getNumberOfPages() + count;
doc.close();
}
} catch (Exception e) {
continue;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
try (PrintStream out = new PrintStream(new FileOutputStream("NumberOfPages.txt"))) {
out.print(count);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void append(String absolutePath) {
textComponent.append(absolutePath + "\n");
}
}
when it gets to the `append(absoluteFile); part thats where the problem lies as it only appends on windows not linux.
UPDATE: I figured that opening it from a different file manager with double click, makes it work. With Nautilus is does not open, even when i choose to run it with java 8 or 9. Opening it with thunar(Different file manager) makes it work no problem with double clicking it. Both are set to run with java 9. I think it has something to do with folder permissions because if i run nautilus as root user, it works when double clicking.

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.

Trying to copy files in specified path with specified extension and replace them with new extension

I have most of it down but when I try to make the copy, no copy is made.
It finds the files in the specified directory like it is supposed to do and I think the copy function executes but there aren't any more files in the specified directory. Any help is appreciated. I made a printf function that isn't shown here. Thanks!
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Stuff {
static String path, oldExtn, newExtn;
static Boolean delOrig = false;
private static void getPathStuff() {
printf("Please enter the desired path\n");
Scanner in = new Scanner(System.in);
path = in.next();
printf("Now enter the file extension to replace\n");
oldExtn = in.next();
printf("Now enter the file extension to replace with\n");
newExtn = in.next();
in.close();
}
public static void main(String[] args) {
getPathStuff();
File folder = new File(path);
printf("folder = %s\n", folder.getPath());
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.getName().endsWith(oldExtn)) {
printf(fileEntry.getName() + "\n");
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
try {
printf("fileEntry = %s\n", fileEntry.toPath().toString());
Files.copy(fileEntry.toPath(), newFile.toPath(),
REPLACE_EXISTING);
} catch (IOException e) {
System.err.printf("Exception");
}
}
}
}
}`
The problem is that the new file is created without a full path (only the file name). So your new file is created - only not where you expect...
You can see that it'll work if you'll replace:
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
with:
File newFile = new File(fileEntry.getAbsolutePath()
.substring(0,
fileEntry.getAbsolutePath()
.lastIndexOf(".")+1) + newExtn);

Categories