Create file in java on linux

Create a folder and a file with Java in Ubuntu

Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn’t create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:

File folder = new File("D:\\temp"); if (folder.exists() && folder.isDirectory()) < >else < folder.mkdir(); >String filePath = folder + File.separator; File file = new File(filePath + "xxx.xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); // more code here 

Please, accept one of the following answer if your question is fulfilled (even if it’s not mine, obviously)

7 Answers 7

Linux does not use drive letters (like D:) and uses forward slashes as file separator.

You can do something like this:

File folder = new File("/path/name/of/the/folder"); folder.mkdirs(); // this will also create parent directories if necessary File file = new File(folder, "filename"); StreamResult result = new StreamResult(file); 

You directory (D:\temp) is nos appropriate on Linux.

Please, consider using linux File System, and the File.SEPARATOR constant :

static String OS = System.getProperty("OS.name").toLowerCase(); String root = "/tmp"; if (OS.indexOf("win") >= 0) < root="D:\\temp"; >else < root="/"; >File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2"); if (folder.exists() && folder.isDirectory()) < >else

Didn’t tried it, but whould work.

Nope. If you create a folder to D:\something linux creates a folder named D:\something in your user directory (tried it)

I will be more accurate, but I meany «D:\temp», I didn’t see Shase doubled it. You’re right it works, I always complain about my colleagues that left thos kind of path in log4j configuration 🙂

root=»/»; It not good solution because not each user can write to root . More correct write to /tmp or home directory.

D:\temp does not exists in linux systems (what I mean is it interprets it as if it were any other foldername)

In Linux systems the file seperator is / instead of \ as in case of Windows

File folder = new File("D:\\temp"); 

Nope. If you create a folder to D:\something linux creates a folder named D:\something in your user directory (tried it)

Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.

Consider both solutions using the getProperty static method of System class.

String os = System.getProperty("os.name"); if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix File folder = new File("/home/tmp"); else if(os.indexOf("win") >= 0) // Windows File folder = new File("D:\\temp"); else throw Exception("your message"); 

On Unix-like systems no logical discs. You can try create on /tmp or /home Below code for create temp dirrectory in your home directory:

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\"; System.out.println(myPathCandidate); //Check write permissions File folder = new File(myPathCandidate); if (folder.exists() && folder.isDirectory() && folder.canWrite()) < System.out.println("Create directory here"); >else

or, for /tmp — system temp dicecrory. Majority of users can write here:

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\"; 

Since Java 7, you can use the Files utility class, with the new Path class. Note that exception handling has been omitted in the examples below.

// uses os separator for path/to/folder. Path file = Paths.get("path","to","file"); // this creates directories in case they don't exist Files.createDirectories(file.getParent()); if (!Files.exists(file)) < Files.createFile(file); >StreamResult result = new StreamResult(file.toFile()); transformer.transform(source, result); 

this covers the generic case, create a folder if it doesn’t exist and a file on that folder.

Читайте также:  Linux mint grub2 установка

In case you actually want to create a temporary file, as written in your example, then you just need to do the following:

// this create a temporary file on the system's default temp folder. Path tempFile = Files.createTempFile("xxx", "xml"); StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); transformer.transform(source, result); 

Note that with this method, the file name will not correspond exactly to the prefix you used ( xxx , in this case).

Still, given that it’s a temp file, that shouldn’t matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.

Источник

How to Create/Write a File in Java?

Java provides a predefined class named “File” which can be found in the java.io package. The File class assists us in working with the files as it provides a wide range of methods such as mkdir(), getName(), and many more. If we talk about file creation and writing to the file, the createNewFile(), and write() methods of the File and FileWriter classes can be used respectively.

This write-up provides a profound understanding of the following concepts:

  • How to Create a File in Java
  • How to Write Data to a File in Java
  • Practical Implementation of createNewFile() and write() methods

How to Create a File in Java

The file class provides a createNewFile() method that makes it possible to create an empty file and if a file is created successfully then it returns true, and if the file already exists then we will get a false value.

Example
The below-given code imports two classes: File and IOException of the java.io package:

package filehandlingexample ;
import java.io.File ;
import java.io.IOException ;

public class FileCreationExample {
public static void main ( String [ ] args ) {
try {
File newFile = new File ( «C:JavaFile.txt» ) ;
if ( newFile. createNewFile ( ) ) {
System . out . println ( «File created: » + newFile. getName ( ) ) ;
} else {
System . out . println ( «File Already Exists» ) ;
}
} catch ( IOException excep ) {
System . out . println ( «Error» ) ;
excep. printStackTrace ( ) ;
}
}
}

To create a file, we utilize the object of the File class with the createNewFile() method and the getName() method is used to get the specified name of the File. Moreover, to tackle the exceptions we utilize the try, catch statements, and within the try block, we utilize the if-else statements to handle two possibilities: file created and file already exists. While the catch block will execute to throw an exception:

Читайте также:  Linux default group for user

The above snippet authenticates that the file created successfully.

How to Write Data to a File using write() method in Java

Java provides a built-in class FileWriter that can be used to write data to any file and to do so, the FileWriter() class provides a write() method. While working with the FileWriter class we have to utilize the close() method to close the file.

Example
Let’s consider the below code snippet that writes the data to a file:

public class FileWriteExample {
public static void main ( String [ ] args ) {
try {
FileWriter fileObj = new FileWriter ( «JavaFile.txt» ) ;
fileObj. write ( «Welcome to LinuxHint» ) ;
fileObj. close ( ) ;
System . out . println ( «Data written to the file Successfully» ) ;
} catch ( IOException e ) {
System . out . println ( «Error» ) ;
e. printStackTrace ( ) ;
}
}
}

In the above code snippet, we created an object of the FileWriter class, and within the parenthesis, we specified the file name to whom we want to write the data. Next, we utilize the write() method of the same class to write the data to the file and then close the file using the close() method. Finally, we handled the exceptions in the catch block using the IOException class.

The output validates that the write() method succeeds in writing the data to a file.

Conclusion

In java, the createNewFile(), and write() methods of File and FileWriter classes can be used respectively to create a file and to write data to a specific file. Moreover, we have to utilize the close() method when working with the FileWriter class to close the File. This write-up presents a comprehensive overview of how to create a file and how to write data to a file in java.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

Java – Create a File

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Читайте также:  Astra linux service status

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Building or modernizing a Java enterprise web app has always been a long process, historically. Not even remotely quick.

That’s the main goal of Jmix is to make the process quick without losing flexibility — with the open-source RAD platform enabling fast development of business applications.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Simply put, a single Java or Kotlin developer can now quickly implement an entire modular feature, from DB schema, data model, fine-grained access control, business logic, BPM, all the way to the UI.

Jmix supports both developer experiences – visual tools and coding, and a host of super useful plugins as well:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Источник

Оцените статью
Adblock
detector