I have a java application running into a weblogic server.
The application have to write a file into the path \bla\john doe (for example).
For this, I used the java.io.File library to:
1. Verify if the path exists
2. If not, create it.
3. Verify if the file exists
4. if not, create it
5. Write the bytes into the file.
The correct behavior would be to create the directory bla into the root of the weblogic's current domain and then create a john doe inside it.
The problem is: in my current enviroment it works like a charm, but in the client's one, the application does not consider the backslash as an element of the path, and instead of creating two directories, the application only creates one, literally named as \bla\john does.
So, instead of:
-domain_root
-bla
-john does
I get the following:
-domain_root
-\bla\john does
(and if I escape it, occurres the same but with two backslash)
The odd is that if I use the commom slash (/bla/john doe), it works..
-domain_root
-bla
-john does
Does any one knows what possibly can be happening?
script for check the path
public File checkPath(String path) {
File f = new File(cls_Util.NeutralizeFilePath(path));
if (!(f.exists() && f.isDirectory())) {
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for check the file:
public File checkFile(String path){
File f = new File(path);
return checkFile(f);
}
public File checkFile(File f) {
if (!(f.exists() && f.isFile())) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for create file
public File writeFile(String path, byte[] binaryfile) {
File file = checkFile(path);
if (file != null) {
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
try {
fos.write(binaryfile);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return file;
}
return null;
}
And to create the file:
String filePathPub = pathPub + newName;
File FilePathPub = writeFile(filePathPub, p_Arquivo);
On Windows the \ starts an absolute path; on Unix/Linux the backslash is a valid filename character (and therefore starts a relative path).
I would suggest you try to avoid using file name concatenation platform specific separators if you are not familiar with the semantic:
File current = new File();
File bla = new File(current, "bla");
(or simply stick to / (forward slash as used by Unix) to separate path components). Java translates this to the Windows character automatically).
Related
so I am generating files and I need to zip them to create a "Resourcepack" for Minecraft.
So on the surface, it looks like the file zips perfectly fine, however I have found some very strange behaviour. In windows, if you zip the directory itself, minecraft will not accept the zip however if you zip the contents, it will work. By the looks of it, this code achieves the first, but I can't manage to find a way to do the latter. The SHA1 of the different Zips are different so there is something going on that I cant see. When viewed they are exactly the same contents.
the code:
public static void pack(String sourceDirPath, String zipFilePath){
sourceDirPath = getDataFolder().getAbsolutePath() + "/" + sourceDirPath;
zipFilePath = getDataFolder().getAbsolutePath() + "/" + zipFilePath;
try {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
}catch (IOException e){
e.printStackTrace();
}
}
EDIT:
I have looking at the properties of the contents of each zip and it looks like the correctly working one is indexing the files im still yet to find anything that allows me to do this
I am trying to make a program that extracts multiple MP4 files from there individual folders and places them in a folder that is already created (code has been changed slightly so that it doesn't mess up any more of the MP4s, rather dummy text files).
I have managed to get so far as to list all folders/files in the specified folder however am having trouble moving them to a directory.
static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");
static void showFiles(File files[]) {
for (File file : files) { // Loops through each file in the specified directory in "dir" variable.
if (file.isDirectory()) { // If the file is a directory.
File[] subDir = file.listFiles(); // Store each file in a File list.
for (File subFiles : subDir) { // Loops through the files in the sub-directory.
if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
source = subFiles.toPath(); // Set source to be the abs path to the file.
System.out.println(source);
try {
Files.move(source, target);
System.out.println("File Moved");
} catch (IOException e) {
e.getMessage();
}
}
}
} else {
source = file.toPath(); // abs path to file
try {
Files.move(source, target);
System.out.println("File moved - " + file.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
showFiles(dir.listFiles());
}
The problem is when I go to move the file from the source folder to the target, it removes or converts the target.
Files.move isn't like the command line. You're programming. You have to spell things out. You're literally asking Files.move to make it so that target (here, G:\GoHere) will henceforth be the location for the file you are moving. If you intended: No, the target is G:\GoHere\TheSameFileName then you have to program this.
Separately, your code is a mess. Stop using java.io.File and java.nio.Path together. Pick a side (and pick the java.nio side, it's an newer API for a good reason), and do not mix and match.
For example:
Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
for (Path child : ds) {
if (Files.isRegularFile(child)) {
Path targetFile = targetDir.resolve(child.getFileName());
Files.move(child, targetFile);
}
}
}
resolve gives you a Path object that is what you need here: The actual file in the target dir.
**I am trying to save and get Player objects from a Textfile and it works when using my IDE but when i create a Jar it can't find the text File. I tried with
this.getClas().getResources(path)
But still it didnt find the path to my text file.Can anybody Help?
public void setPlayer() throws FileNotFoundException {
ArrayList<Player> playerArrayList = new ArrayList<>();
playerArrayList = getPlayers();
Player player = new Player();
player.name = ViewManager.name;
player.score = Collision.points;
playerArrayList.add(player);
try{
FileOutputStream fileOut = new FileOutputStream("src/resources/highscore.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(Player player1 : playerArrayList){
out.writeObject(player1);
}
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
ยดยดยดยด
Resource files are not physical Files, as they can be inside a jar. They are intended to be read-only, and the class loader may cache them. They are case sensitive, with / as path separator and there path starts at the class path's root, probably src/resources.
So use the resource file as fall back resource to copy, if some physical file does not exist.
Path appDir = Paths.get(System.getProperty("user.home") + ".myapp");
Files.createDirectories(appDir);
Path file = appDir.resolve("highscore.txt");
if (!Files.exists(file)) {
// Copy resource to file, either:
URL url = getClass().getResource("/highscore.txt");
Path templatePath = Paths.get(url.toURI());
Files.copy(templatePath, file);
// Or
InputStream templateIn = getClass().getResourceAsStream("/highscore.txt");
Files.copy(templateIn, file);
}
try (FileOutputStream out = Files.newOutputStream(file)) {
...
}
Path is the generalisation of File.
I don't know what IDE you're using, but you're writing the file to the source sub directory. That directory might not be included in the jar.
My purpose is to replace an html file in a folder by another one, so that at the end :
html_link1 will be replaced by html_link2
Is there a way to update HTML files by executing code in Java ?
public static void main(String[] args) {
Path sourceDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
//copy source to target using Files Class
try {
Files.copy(sourceDirectory, targetDirectory,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
I need to find a way to change the URL, since the Path are now the same, the URL of the second HTML file didn't changed
You have to pass the absolute file path untill and unless you wish to replace the whole directory.
Path sourceFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
try {
Files.copy(sourceFilePath , targetFilePath ,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
So long as they actually files, and you have the proper permission for the directory they are in, then you can do this the same way you would for any file.
The code I've written is supposed to overwrite over the contents of the selected text file, but it's appending it. What am I doing wrong exactly?
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
f2 = new FileWriter(fnew,false);
f2.write(source);
/*for (int i=0; i<source.length();i++)
{
if(source.charAt(i)=='\n')
f2.append(System.getProperty("line.separator"));
f2.append(source.charAt(i));
}*/
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
I tried making a new temp.txt file and writing the new contents into that, deleting this text file and renaming temp.txt to this one. Thing is, the deletion is always unsuccessful. I don't think I have to change user permissions for this do I?
Also, a part of my program lists all the files in this directory, so I'm guessing they're being used by the program and so can't be deleted. But why not overwritten?
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold=new File("../playlist/"+existingPlaylist.getText()+".txt");
fold.delete();
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Your code works fine for me. It replaced the text in the file as expected and didn't append.
If you wanted to append, you set the second parameter in
new FileWriter(fnew,false);
to true;
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the
first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field
of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}