Creating a simple data output file in Java - java

I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.

On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));

Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work

You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.

To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}

Related

How to write file path into txt.file?

I am writing simple program that is looking for file and if it exists, writes his path to txt file. If not, program is freezed for 1 minute. My problem is that file path is not being printed into txt file when searched file exists. I think it is something wrong with try block. I do not know where the problem is. How can i solve it?
public class FileScanner {
public void scanFolder() throws IOException, InterruptedException {
Scanner input = new Scanner(System.in);
//tworzenie pliku logu
File log = new File("C:/Users/mateu/OneDrive/Pulpit/log.txt");
if (!log.exists()) {
log.createNewFile();
}
//obiekt zapisujacy nazwy i sciezki plikow do logu
PrintWriter printIntoLog = new PrintWriter(log);
while (true) {
//podanie sciezki szukanego pliku
System.out.println("Input file's directory you are looking for: ");
String path = input.nextLine();
//utworzenie obiektu do danego pliku
File searchedFile = new File(path);
//sprawdzenie czy plik istnieje- jesli tak to zapisuje do logu jego sciezke i usuwa go
try{
if (searchedFile.exists()) {
printIntoLog.println(searchedFile.getPath());
//searchedFile.delete();
}else{
throw new MyFileNotFoundException("Searching stopped for 1 minute.");
}
}catch(MyFileNotFoundException ex){
System.out.println(ex);
TimeUnit.MINUTES.sleep(1);
}
}
}
}
You should close the PrintWriter reference before finishing execution. It's an enforced practice to close a file after read/write on it.
If you are using Java +7 you can use the fancy way withtry-with-resources syntax
```java
try (PrintWriter printIntoLog = new PrintWriter(log)) {
while (true) {
....
}
}
```
With older versions you can use try-finally syntax
try {
while(true) {
...
}
} finally {
printIntoLog.close();
}
See
Java – Try with Resources

Is there any way to specify the file name to read using byte streams within the source code in java?

Background
From the examples that I've seen so far, when you read files using byte streams in java, you have to specify the file name in command prompt. I writing a Java program that I need the file name to be specified in the source code. For example:
/* Display a text file.
To use this program, specify the name of the file that you want to see.
For example, to see a file called TEST.TXT, use the following command line.
java ShowFile TEST.TXT
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Question
Is there any way to specify the file name to read using byte streams within the source code?
The first google result for "java open file byte stream" shows you how to do this. And it's the main java documentation.
Edit:
Based on your code sample
fin = new FileInputStream("myFilenameExample");

FileInputStream("hello.txt"), doesn't work unless I specify an absolute path (C:\User\Documents etc)

Hi is there any way I can get FileInputStream to read hello.txt in the same directory without specifying a path?
package hello/
helloreader.java
hello.txt
My error message: Error: .\hello.txt (The system cannot find the file specified)
You can read file with relative path like.
File file = new File("./hello.txt");
YourProject
->bin
->hello.txt
->.classpath
->.project
Here is works
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class fileInputStream {
public static void main(String[] args) {
File file = new File("./hello.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You can use YourClassName.class.getResourceAsStream("Filename.txt"), but your text file has to be in the same directory/package as your YourClassName file.
When you open "hello.txt" you are opening a file in the current working directory of the process. i.e. where the program was run from, not where your jar is or some other directory.
When you open your file with path hello.txt, the file hello.txt should be in the same directory of where you execute the java command, that is the working directory. And you can use the following code to print the working directory when you run a Java program:
System.out.println(System.getProperty("user.dir"));
Suppose you execute your code like this java hello.helloreader, then you should use the following path to get the hello.txt:
new FileInputStream("hello/hello.txt")
you can try System.getProperty("dir") to show your current directory, and you will know how to write your file path

No such file or directory error on a mac

I'm trying to read a file that exists in the following location of my Eclipse java project:
Tester -> src -> threads -> ReadFile.java
This is the code used:
public class Tester {
public static void main(String[] args) {
ReadFile[] readers;
readers = new ReadFile[3];
for (int intLoopCounter = 0; intLoopCounter < 3; intLoopCounter++) {
readers[intLoopCounter] =
new ReadFile("ReadFile.java", intLoopCounter);
System.out.println("Doing thread number: " + (intLoopCounter + 1));
}
}
Can you tell me what to add to:
new ReadFile("ReadFile.java"
so the file can be read?
There is a buffered reader in the ReadFile.java class file. I'm experimenting with this just to see if I can read the ReafFile.java file and show the results to the console.
Here is the code that is throwing the error from ReadFile.java:
public ReadFile(String filename, int i) {
id = i;
try {
input = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Problem occured: " + e.getMessage());
} // catch
} // Constructor
Assuming that Tester is your project root directory, your path to the file should be "src/threads/ReadFile.java". If the file trully exists it will be found.
You need to modify the path in the call to ReadFile to include a full path, a path anchored by your user directory, or a path relative to the directory in which Eclipse runs your test program.
For example, if your project is located in /Users/myuser/projects/Tester/src/threads, you can use this line:
new ReadFile("/Users/myuser/projects/Tester/src/threads/ReadFile.java", intLoopCounter)

problem with deleting files

private static void deletefile(String file) {
int fileName = 500;
int z;
String[] File = new String[fileName];
for (z = 0; z < fileName; z++) {
File f1 = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + z
+ ".txt");
boolean success = f1.delete();
if (!success) {
System.out.println("Deletion failed.");
System.exit(0);
} else {
System.out.println("File deleted.");
}
}
}
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("File has not mentioned.");
System.exit(0);
case 1:
deletefile(args[0]);
System.exit(0);
default:
System.out.println("Multiple files are not allow.");
System.exit(0);
hi, this is my code for attempting to delete a certain files in java. It prints out file has not mentioned.i was trying to delete a set of txt files in a certain folder. The program should continue with the next file once a file is missing. Can anyone point out my mistake ? thanks..
Apparently you did not pass any command line parameters to your program.
(Although even if you did, it is not used anywhere in deletefile() - your method attempts to delete a fixed set of files in a specific directory, and if any of these is missing or you don't have permissions to delete it, it exits with an error message.)
You have to specify the file name as command line argument when running your Java program.
java MyClass file_to_delete
You need to have some check or catch exception when you create a new file so it wont stop when the file is not found.

Categories

Resources