I want to save my output as a separate at a specified folder. The following code would save the output at the project root. How can I change it?
public static void main(String[] args) throws Exception {
FileOutputStream f = new FileOutputStream("file.txt");
System.setOut(new PrintStream(f));
System.out.println("This is System class!!!");
}
Besides, I have tried to change the "Run Configurations"-> "Common"-> "Output File" in Eclipse, but it doesn't help me.
Intead of passing directly the Filename to the FileOutputStream you need to pass it a File instance like this:
File directoryLogs = new File("logs");
fileDirectory.mkdirs(); // Create the directory (if not exist)
File fileLog = new File(directoryLogs, "log.txt");
fileLog.createNewFile(); // Create the file (if not exist)
then
public static void main(String[] args) throws Exception {
// Create a log directory
File directoryLogs = new File("logs");
fileDirectory.mkdirs();
// Create a log file
File fileLog = new File(directoryLogs, "log.txt");
fileLog.createNewFile();
// Create a stream to to the log file
FileOutputStream f = new FileOutputStream(fileLog);
System.setOut(new PrintStream(f));
System.out.println("This is System class!!!");
// You should close the stream when the programs end
f.close();
}
If you want completly change the path of logs directory you could also specify
an absolute path here
// NB: Writing directly to C:\ require admin permission
File directoryLogs = new File("C:\\MyApplication\\logs");
Related
Is there a way to use the File class to create a new text file? After doing some research, I tried:
import java.io.*;
public class createNewFile
{
public static void main(String args[]) throws IOException
{
File file = new File("newfile.txt");
boolean b1 = file.createNewFile();
}
}
...but there is still no newfile.txt in my source directory. It would also seem like there would be a void method to do this, instead of having to result to a boolean. Is there a way to do what I'm trying to do with the FIle class, or so I have to result to another class?
You have created a file but apparently not in your source directory but in the current working directory. You can find the location of this new file with:
System.out.println(file.getAbsolutePath());
One possibility to control the location of the new file is to use an absolute path:
File file = new File("<path to the source dir>/newfile.txt");
file.createNewFile();
You can try like this:
File f = new File("C:/Path/SubPath/newfile.txt");
f.getParentFile().mkdirs();
f.createNewFile();
Also make sure that the path where you are checking and creating the file exists.
i can seem to understand why my code isn't compiling. Everytime I run it, I get a FILENOTFOUNDException. Any help would be much appreciated. :D
public static void main(String args[]) throws IOException
{
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
for(int empNum = 1; empNum<=3; empNum++)
{
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner)
{
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
Basically the exception message means the filename you specified is not an existing file in executions directory.
EDIT[copied from my comment]
That file should be located where compilation is done, if you are using eclipse or intellij it should be at your projects root directory.
+ Because you are passing in a relative path and not an absolute one to the file, java is recognizing it as a relative to execution directory which is located where followin code points to.
To check what is that desired input files directory simply use
getAbsolutePath() on that file.
For instance:
File input = new File("EmployeeInfo.txt");
System.out.println("Move .txt to dir:" + input.getAbsolutePath());
Scanner diskScanner = new Scanner(input);
Then move the source .txt file to that location
My goal
I am trying to write simple objects (SimpleType) into files, so that the files can be loaded later and the objects recreated.
My setting
I am currently working in the NetBeans IDE (JDK8) on a Windows 7 machine. I don't think that should make a difference, though.
This is the type I would like to write into the file:
public class SimpleType implements Serializable {
boolean[] a;
boolean[] b;
}
This is the code I'm trying to get to run:
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
String fileName = "test.txt";
SimpleType foo = new SimpleType;
try (ObjectOutputStream out = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(fileName)))) {
out.writeObject(foo);
out.close();
}
}
}
My problem
The code compiles and runs, but always throws a FileNotFoundException:
Exception in thread "main" java.io.FileNotFoundException: test.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:33)
My attempts to fix it
According to the documentation, I would expect the file to be created if it doesn't exist already. I've thoroughly read the Javadoc for the method I attempt to use, an excerpt of which I cite here (emphasis mine):
public FileOutputStream(String name) throws FileNotFoundException
[...]
Parameters:
name - the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather
than a regular file, does not exist but cannot be created, or cannot
be opened for any other reason
SecurityException - if a security manager exists and its checkWrite
method denies write access to the file.
I am sure that I have read/write permissions in the directory; there is no existing file with the name test.txt so it cannot be locked by another program.
Changing fileName to an absolute path I am sure I can write into doesn't make any difference.
It is reproducible if file is in read-only mode. Can you try like this.
public static void main(String[] args) {
String fileName = "sampleObjectFile.txt";
SampleObject sampleObject = new SampleObject();
File file = new File(fileName);
file.setWritable(true); //make it writable.
try(ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
outputStream.writeObject(sampleObject);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are writing the file on OS disk you need admin privileges. so avoid writing on OS disk.
Normally this is because you are trying to write on a location not allowed by your FileSystem (for example in Windows7 you cannot write a new file in c:). Try to investigate where the program is trying to write using procmon from Microsoft's SysInternals. Add a new filter (path contains test.txt) and see what happens.
I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
I am trying to createNewFile() in java.I have written down the following example.I have compiled it but am getting a run time error.
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String [] args)
{
try
{
File file = new File("home/karthik/newfile.txt");
if(file.createNewFile())
{
System.out.println("created new fle");
}else
{
System.out.println("could not create a new file");
}
}catch(IOException e )
{
e.printStackTrace();
}
}
}
It is compiling OK.The run time error that I am getting is
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFileExample.main(CreateFileExample.java:16)
some points here
1- as Victor said you are missing the leading slash
2- if your file is created, then every time you invoke this method "File.createNewFile()" will return false
3- your class is very platform dependent (one of the main reasons why Java is powerful programming language is that it is a NON-PLATFORM dependent), instead you can detect a relative location throw using the System.getProperties() :
// get System properties :
java.util.Properties properties = System.getProperties();
// to print all the keys in the properties map <for testing>
properties.list(System.out);
// get Operating System home directory
String home = properties.get("user.home").toString();
// get Operating System separator
String separator = properties.get("file.separator").toString();
// your directory name
String directoryName = "karthik";
// your file name
String fileName = "newfile.txt";
// create your directory Object (wont harm if it is already there ...
// just an additional object on the heap that will cost you some bytes
File dir = new File(home+separator+directoryName);
// create a new directory, will do nothing if directory exists
dir.mkdir();
// create your file Object
File file = new File(dir,fileName);
// the rest of your code
try {
if (file.createNewFile()) {
System.out.println("created new fle");
} else {
System.out.println("could not create a new file");
}
} catch (IOException e) {
e.printStackTrace();
}
this way you will create your file in any home directory on any platform, this worked for my windows operating system, and is expected to work for your Linux or Ubuntu as well
You're missing the leading slash in the file path.
Try this:
File file = new File("/home/karthik/newfile.txt");
That should work!
Actually this error comes when there is no directory "karthik" as in above example and createNewFile() is only to create file not for directory use mkdir() for directory and then createNewFile() for file.