DirectoryNotEmptyException exception unknowingly why - java

I have the following code that should replace an image in a folder inside Local AppData, although I get an exception saying "java.nio.file.DirectoryNotEmptyException: C:\Users\user\AppData\Local\Roblox\Versions\version-76a406688204424a\content\textures". What can I do?
Code:
package robloxstudioclassimageloader;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
public class RobloxStudioClassImageLoader {
private static Path pathFile = Paths.get("resources/ClassImages.png");
private static Scanner scanner;
private static String path;
private static Path textureFile;
public static void main(String[] args) {
try{
scanner = new Scanner(new File("resources/path.txt"));
}catch(Exception e){
System.out.println(e);
}
path = scanner.nextLine();
textureFile = Paths.get(path);
File RobloxPath = new File(path);
if(RobloxPath.isDirectory()){
for (final File versionEntry : RobloxPath.listFiles()) { //versions folder
if (versionEntry.isDirectory()) {
for (final File contentEntry : versionEntry.listFiles()) { //version folder
if (contentEntry.isDirectory()) {
if(contentEntry.getName().equals("content")){
for (final File contentEntry2 : contentEntry.listFiles()) { //content folder
if (contentEntry2.getName().equals("textures")) {
for (final File textureEntry : contentEntry2.listFiles()) { //texture file
if(textureEntry.getName().equals("ClassImages.PNG") || textureEntry.getName().equals("ClassImages.png")) {
System.out.println(textureEntry.getName());
Path endPath = Paths.get(textureEntry.getParent());
System.out.println(endPath);
try{
Files.copy(pathFile,endPath,StandardCopyOption.REPLACE_EXISTING);
}catch(Exception e){
System.out.println(e);
}
System.out.println("ENDED");
System.exit(0);
break;
}
}
}
}
}
}
}
}
}
}
System.exit(0);
}
}

Related

How I can create TOC using apache poi

I have the code which create table of content like this:
image screenshot ,
but i want resualt like this:
image screenshot ,
and this is my code
package com.example;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.dump.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
These are libraries which I'm using for this project
and I'm also using the maven package manager
public class toc {
public static void main(String[] args) throws IOException, OpenXML4JException {
XWPFDocument docTemplate = null;
try {
File file = new File(
"outfile02.docx"); // "C:\\Reports\\Template.docx";
FileInputStream fis = new FileInputStream(file);
docTemplate = new XWPFDocument(fis);
generateTOC(docTemplate);
saveDocument(docTemplate);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (docTemplate != null) {
docTemplate.close();
}
}
}
save function
private static void saveDocument(XWPFDocument docTemplate) throws FileNotFoundException, IOException {
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream("outfile03.docx");
docTemplate.write(outputFile);
} finally {
if (outputFile != null) {
outputFile.close();
}
}
}
TOC generator function
public static void generateTOC(XWPFDocument document)
throws InvalidFormatException, FileNotFoundException, IOException {
String findText = "${TOC}";
String replaceText = "";
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
int pos = r.getTextPosition();
String text = r.getText(pos);
if (text != null && text.contains(findText)) {
text = text.replace(findText, replaceText);
r.setText(text, 0);
addField(p, "TOC \\o \"1-3\" \\h \\z \\u");
break;
}
}
}
}
and this is last function
private static void addField(XWPFParagraph paragraph, String fieldName) {
CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
// ctSimpleField.setInstr(fieldName + " \\h ");
ctSimpleField.setInstr(fieldName);
ctSimpleField.addNewR().addNewT().setStringValue("outfile03.docx");
}
}

How can I change just some part of a name in a file in Java?

I have a file called "ParkPhotos.txt" and inside I have 12 names of some parks, for example "AmericanSamoa1989_photo.jpg". I want to replace the "_photo.jpg" to "_info.txt", but I am struggling. In the code I was able to read the file, but I am not sure how to replace it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws IOException
{
readFileValues();
}
public static void readFileValues() throws IOException
{
try {
File aFile = new File("ParkPhotos.txt");
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine())
{
String parkNames = inFile.nextLine();
System.out.println(parkNames);
}
inFile.close();
} catch (FileNotFoundException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
}
}
You can convert to a new content and write it to the current file. For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws URISyntaxException {
String newContent = readFileValues();
writeFileValues(newContent);
}
public static String readFileValues() {
StringBuilder newContent = new StringBuilder();
try {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine()) {
String parkName = inFile.nextLine();
if (parkName == null || parkName.isEmpty()) {
continue;
}
newContent.append(parkName.replace("_photo.jpg", "_info.txt"))
.append(System.lineSeparator());
}
inFile.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
return newContent.toString();
}
public static void writeFileValues(String content) throws URISyntaxException {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
try (FileWriter writer = new FileWriter(aFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: the file will be written at build folder. For example: example_1/build/resources/main

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);
}
}

How to unzip all the password protected zip files in a directory using Java

I am new to java and trying to write an program which will unzip all the password protected zip files in an directory, I am able to unzip all the normal zip files (Without password) but I am not sure how to unzip password protected files.
Note: All zip files have same password
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import java.util.zip.*;
public class Extraction {
// public Extraction() {
//
// try {
//
// ZipFile zipFile = new
// ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");
//
// if (zipFile.isEncrypted()) {
//
// zipFile.setPassword("CLAIMS!");
// }
//
// List fileHeaderList = zipFile.getFileHeaders();
//
// for (int i = 0; i < fileHeaderList.size(); i++) {
// FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//
// zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
// System.out.println("Extracted");
// }
//
// } catch (Exception e) {
// System.out.println("Please Try Again");
// }
//
// }
//
// public static void main(String[] args) {
// new Extraction();
//
// }
// }
public static void main(String[] args) {
Extraction unzipper = new Extraction();
unzipper.unzipZipsInDirTo(Paths.get("C:\\Users\\Desktop\\ZipFile"),
Paths.get("C:\\Users\\Desktop\\ZipFile\\Unziped"));
}
public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {
final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
try (final Stream<Path> stream = Files.list(searchDir)) {
stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
} catch (Exception e) {
System.out.println("Something went wrong, Please try again!!");
}
}
public void unzip(Path zipFile, Path outputPath) {
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
Path newFilePath = outputPath.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(newFilePath);
} else {
if (!Files.exists(newFilePath.getParent())) {
Files.createDirectories(newFilePath.getParent());
}
try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
byte[] buffer = new byte[Math.toIntExact(entry.getSize())];
int location;
while ((location = zis.read(buffer)) != -1) {
bos.write(buffer, 0, location);
}
}
}
entry = zis.getNextEntry();
}
} catch (Exception e1) {
System.out.println("Please try again");
}
}
}
I found the answer I am posting this as there might be someone else who might be looking for the similar answer.
import java.io.File;
import java.util.List;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
public class SamExtraction {
public static void main(String[] args) {
final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
//Folder where zip file is present
final File file = new File("C:/Users/Desktop/ZipFile");
for (final File child : file.listFiles()) {
try {
ZipFile zipFile = new ZipFile(child);
if (extensionFilter.accept(child)) {
if (zipFile.isEncrypted()) {
//Your ZIP password
zipFile.setPassword("MYPASS!");
}
List fileHeaderList = zipFile.getFileHeaders();
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//Path where you want to Extract
zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
System.out.println("Extracted");
}
}
} catch (Exception e) {
System.out.println("Please Try Again");
}
}
}
}

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.

Categories