Cannot walk directory using Files.walk - java

I am trying to understand why my code won't run.
The example is how to use java.io to find a path directory and print out the title of all .txt files in that directory.
My code is below:
try
{
Files.walk(Paths.get(\\Users\\Name\\Desktop\\Test Folder)).forEach(p -> {
if (p.getFileName().toString().endsWith(".txt")) {
System.out.println("Text doc: " + p.getFileName());
}
});
} catch (IOException e) {
e.printStackTrace();
}
I am currently importing java.io.IOException, java.nio.file.Files, and java.nio.file.Paths.
The error I am getting is java.nio.file.NoSuchFileException: myDirPath.
If anyone can help, or at least point me in the right direction I would be very grateful.

try
{
Files.walk(Paths.get("/Users/Jayden/Desktop/Test Folder")).forEach(p -> {
if (p.getFileName().toString().endsWith(".txt")) {
System.out.println("Text doc: " + p.getFileName());
}
});
} catch (IOException e) {
e.printStackTrace();
}
I was not using slashes properly.

Related

Springboot async upload and store method using multipart file problem

I am trying to make async upload service with spring boot, here is my code:
public ResponseEntity<?> save(MultipartFile[] files) {
if (files.length == 0) {
return ResponseEntity.badRequest().body("No files selected");
}
DigikyblikFileStorage storage = digikyblikFileStoragesService.getIdealStorage();
UUID bucketUUID = UUID.randomUUID();
asyncService.saveFiles(files, storage, bucketUUID);
try {
List<File> filesData = new ArrayList<>();
for (MultipartFile file : files) {
filesData.add(new File(file.getOriginalFilename(), file.getSize()));
}
BucketFilesRecord record = new BucketFilesRecord();
record.setBucketUUID(bucketUUID);
record.setStorageId(storage.getId());
record.setFilesInfo(new ObjectMapper().writeValueAsString(filesData));
bucketFilesRecordRepository.save(record);
} catch (JsonProcessingException e) {
logger.error("Error when setting files info for bucketUUID: " + bucketUUID, e);
return ResponseEntity.internalServerError().body("Error when setting files info for bucketUUID: " + bucketUUID);
} catch (IOException e) {
logger.error("Error when getting bytes from multipart files for bucketUUID: " + bucketUUID, e);
}
return new ResponseEntity<>(new FilesUploadedResponse(bucketUUID), HttpStatus.OK);
}
and :
#Async
public void saveFiles(MultipartFile[] files, DigikyblikFileStorage storage, UUID bucketUUID) {
logger.info("Start storing files for bucketUUID: " + bucketUUID);
Path filesPath = Paths.get(storage.getStoragePath() + java.io.File.separator + bucketUUID);
try {
Files.createDirectories(filesPath);
} catch (IOException e) {
logger.error("Couldn't create directories for bucketUUID: " + bucketUUID, e);
return;
}
for (MultipartFile file : files) {
Path path = Paths.get(filesPath + java.io.File.separator + file.getOriginalFilename());
try {
file.transferTo(path);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sometimes it works well, but sometimes i get this error:
java.nio.file.NoSuchFileException: /media/wedos-test/upload_814fc87f_9641_48be_adb4_c79f0111f11c_00000012.tmp
I know why, its because that spring delete tmp folder before file transaction is done, but i dont know how this could be repared, one solution was that a could read bytes and then call async method, so tmp directory shouldnt be needed anymore, but when i try upload bigger files with this solution, i get of course memory error. Can anyone help me with this problem? Thanks!
I think the second comment from that answer could help you. It says that you can create your own temp file on disk and work with it while needed. In that scenario you don't need to think about memory.
And take a look at approach number 2. It suggests to use MultiPartFile implementation with custom constructor and then use it in your logic.

Java - How to move files using FileUtils?

Everyone keeps saying how simple it is to move a file from point a to point b using fileutils, but I'm having lots of trouble moving a file :(
I have a /temp/ folder in the directory wherever the .jar is located, in this temp folder I have a .txt file I want to move up a directory (so basically next to the .jar file) but I cant seem to do it?
Here's some code, but I know its not even close:
public void replaceFile() {
String absolutePath = getPath();
Path from = Paths.get(absolutePath + "\\temp\\test.txt");
Path to = Paths.get(absolutePath + "\\test.txt");
try {
FileUtils.moveFile(FileUtils.getFile(from.toAbsolutePath().toString()), FileUtils.getFile(to.toAbsolutePath().toString()));
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getPath() {
File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
//JOptionPane.showMessageDialog(null, jarDir.getAbsolutePath());
return jarDir.getAbsolutePath();
}
Any help is appreciated :\
Why don't use this Java API for Moving a File or Directory
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
UPDATE
Looking at your source code I suggest the following implementation:
Path from = Paths.get(absolutePath, "/temp/test.txt");
Path to = Paths.get(absolutePath, "/test.txt");
try {
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ok i managed to do it, apparently the getPath() method returned some funny path and it failed there, so heres a code that works
public void downloadJar() {
String absolutePath = getPath();
String from = absolutePath + "\\temp\\test.txt";
String to = absolutePath + "\\test.txt";
File fileTo = new File(to);
File fileFrom = new File(from);
try {
FileUtils.moveFile(fileFrom, fileTo);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "io exce");
}
}
public String getPath() {
return System.getProperty("user.dir");
}
thanks everyone

OutputStreamWriter contains a path separator

Today i tested "files" instead of a normal path.
Here is my code:
File path=new File(getFilesDir(),"uf");
File test = new File(path.getAbsolutePath(),"test.txt");
if(!path.exists()){
path.mkdir();
}
if(!test.isFile()){
try {
test.createNewFile();
} catch (IOException e) {
//TODO in errorlog -> filecreation
e.printStackTrace();
}
}else{
try {
OutputStreamWriter mywriter = new OutputStreamWriter(openFileOutput(test.getAbsolutePath().toString(),Context.M ODE_PRIVATE));
mywriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
In the error code comes everytime: illegal Arguments: contains a path seperator!
Thank you for your help in advance
Maybe add more info about your error. But...
This error is about that you are trying to full path (include you subdirectories) to access to private data area.
Solution is use FileOutputStream, more here. And use
new File(YOUR_FILE)
to create your file.
Keep on mind that you should call method mkDirs() to create all necessary directories and subdirectories. More about mkDirs() here
Note: There is also method mkDir(), here is doc. This one will create a single directory.

Resources not getting released in java

So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.

FileOuputStream Write bytes for loop, but no data write?

Listing my program fragment as below
public class InStream {
static FileOutputStream file=null;
static {
try {
file = new FileOutputStream("deo.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//when i try to replace below infinite loop,
//it is also not able to output my String
//while(ture)
or
//for(;;)
for(int i=0;i<100000;i++){
file.write("AB ".getBytes());
}
//file.flush();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run this program -> open deo.txt -> there are no data within this file
but when i comment the for loop just only test below fragment code:
try {
file.write("AB ".getBytes());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Now i can see the "AB " string in the file. so strange....
Can any one do me a favor?
There is no error in your code. File "deo.txt" must be generate which contains AB AB...............
I tested your code. And it works. But for the deo.txt. You can check its size if it is about 293k. It displays nothing if you open it with Eclipse text editor. But you can view it with other system editor, such as notepad++.

Categories