File handling in java - java

I have the below code.
The below source code is from the file x.java. The hi.html is present in the same directory as x.java.
I get a file not found exception even though the file is present. Am I missing something ?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Exception e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}

The directory of the .java file is not necessarily the direction your code runs in! You can check the current working dir of your program by in example:
System.out.println( System.getProperty( "user.dir" ) );
You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)

Take a look at your "user.dir" property.
String curDir = System.getProperty("user.dir");
That's where the program will root its search for files that don't have a complete path.

Catch the FileNotFoundException before catching Exception so as to be sure that is the real Exception type.
Since you don't give an absolute location for a file it searches from your working directory. You can store the absolute path in a property file and use that instead or use System.getProperty("user.dir") to return the directory that you are running the Java app from.
Code to get Key-Value from Property files
private void getPropertyFileValues() {
String currentPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "Loader.properties";
FileInputStream fis = null;
try {
fis = new FileInputStream(currentPath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Properties props = new Properties();
try {
props.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
String filePath= props.getProperty("FILE_PATH");
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

I guess you get a NullPointerException:
FileInputStream fis = null;
then the call:
int i = fis.available();
will result in an NullPointerException as the first non-null assignment to fis is later:
fis = new FileInputStream(file);

File Handling in Java:
Use File class for Representing and manipulating file or folder/directory.
you can use constructor :
ex. File file = new File("path/file_name.txt");
or
File file = new File("Path","file_name");
File representation example:
import java.io.File;
import java.util.Date;
import java.io.*;
import java.util.*;
public class FileRepresentation {
public static void main(String[] args) {
File f =new File("path/file_name.txt");
if(f.exists()){
System.out.println("Name " + f.getName());
System.out.println("Absolute path: " +f.getAbsolutePath());
System.out.println("Is writable " +f.canWrite());
System.out.println("Is readable " + f.canRead());
System.out.println("Is File " + f.isFile());
System.out.println("Is Directory " + f.isDirectory());
System.out.println("Last Modified at " + new Date(f.lastModified()));
System.out.println("Length " + f.length() +"bytes long.");
}//if
}//main
}//class

Write data character by character, into Text file by Java:
use FileWriter Class-
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class WriteFile {
public static void main(String[] args) throws Exception{
//File writer takes chars and convert into bytes and write to a file
FileWriter writer = new FileWriter("path/file_name.txt");
//if file not exits then created it, else override data
writer.write('A');
writer.write('E');
writer.write('I');
writer.write('O');
writer.write('U');
writer.close();
System.out.println("Successfully Written");
}
}

Related

Is this correctly writing to a text file?

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java
Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

read and write from Internal storage

I am having this exception when trying to read from the file
java.io.FileNotFoundException: /data/data/.../files
I used this method because it can handle Unicode text while reading from the file
public void save(String string )
{
String filename = "main";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String read()
{
try
{
Reader readerUnicode =
new InputStreamReader(new FileInputStream(getFilesDir()), Charset.forName("UTF-16"));
int e = 0;
String f="";
while ((e = readerUnicode.read()) != -1) {
// cast to char. The casting removes the left most bit.
f = f+Character.toString((char) e);
System.out.print(f);
}
return f;
}
catch(Exception e)
{
return e+"";
}
}
how can I retrieve the internal save path
thanks
You are using getFilesDir() But not setting the actual file name. Just the directory path.
Try adding the file name in. Plus, you should probably add an extension like .txt to both the save and load path.
new InputStreamReader(new FileInputStream(getFilesDir() + "/" + filename ), Charset.forName("UTF-16"));
and change filename to something more sensible.
String filename = "main.txt";
You could/should also check the file exists before accessing it. (Although you do try catch anyway)
File file = new File(getFilesDir() + "/" + filename);
if(!file.exists())
return "";

concatenating .java files in java

so I'm making a java app to find all java files on a directory and then concatenate them into one single file to be put on the same directory but I can't seem to get the concatenation right. Here's what I've done so far hope you guys can help me with it as I've tried various things but still can't get it right. Thanks!
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileConcatenate {
public static void main(String[] args) {
String dirName = args[0];
String fileName = args[1];
File dirFile = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "");
File file = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "\\" + fileName + ".java");
FileFilter filter = new FileFilter(){
public boolean accept(File pathname){
if(pathname.getName().contains(".java")){
return true;
}else{
return false;
}
}
};
try{
if(!dirFile.exists()){
System.out.println("There is no directory with that name");
}
File[] javaFile = dirFile.listFiles(filter);
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
for(File f : javaFile){
FileReader fr = new FileReader(f);
fw.write(fr.read());
fr.close();
}
fw.flush();
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Do in this way. For more info read inline comments.
...
FileWriter fw = new FileWriter(file, true);
for (File f : javaFile) {
FileReader fr = new FileReader(f);
// read 1000 chars at a time from source file
char[] cbuf = new char[1000];
int count = -1;
// iterate till the end of source file
// here count represent the no of chars read at a time
while ((count = fr.read(cbuf)) != -1) {
// write in the targeted file
fw.write(cbuf, 0, count);
}
fr.close();
}
...
In your case fw.write(fr.read()); doesn't do what you are expecting.
It just read one character form the source file and write in the target file.
For more info have a look at InputStreamReader#read() that reads a single character.

java writing file error: java.io.FileNotFoundException: Invalid file path

I have a question about writing csv file on the current project in eclipse
public static void Write_Result(String Amount_Time_Dalta) throws IOException{
File file;
FileOutputStream fop = null;
String content = "";
String All_Result[] = Amount_Time_Dalta.split("-");
String path ="/Users/Myname/Documents/workspace/ProjectHelper/"+All_Result[1] + ".csv";
System.out.println(path);
content = All_Result[3]+ "," + All_Result[5] + "\n";
System.out.println(content);
file = new File(path);
fop = new FileOutputStream(file);
file.getParentFile();
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
}
and I am getting error which is
Exception in thread "main" java.io.FileNotFoundException: Invalid file path
at java.io.FileOutputStream.<init>(FileOutputStream.java:215)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at FileDistributor.Write_Result(FileDistributor.java:59)
at FileDistributor.main(FileDistributor.java:29)
I used
String path ="/Users/Myname/Documents/workspace/ProjectHelper/";
path to read a files. I was working fine.
However, when I am using same path to write result to file ( can be exist or not. I create or overwrite a file.) it returns Invalid file path.... I am not really sure why..
updated
just found interesting thing. when i just use File newTextFile = new File("1000".csv); then it is working. however, when i replace to File newTextFile = new File(filename +".csv"); it doesn't work.
What you have here is a valid path from which a File object can be created:
/Users/Myname/Documents/workspace/ProjectHelper/
But if you look at it a second time, you'll see that it refers to a directory, not a writable file. What's your file name?
What does your System.out.println say is the value of All_Result[1]?
Sample Code:
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args)
{
String[] array = {"1000.csv", "800.csv", "700.csv"};
File file;
FileOutputStream fop;
// Uncomment these two lines
//String path = "c:\\" + array[0];
//file = new File(path);
// And comment these next two lines, and the code still works
String path = "c:\\";
file = new File (path + array[0]);
// Sanity check
System.out.println(path);
try
{
fop = new FileOutputStream(file);
}
catch(IOException e)
{
System.out.println("IOException opening output stream");
e.printStackTrace();
}
if (!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
System.out.println("IOException opening creating new file");
e.printStackTrace();
}
}
}
}
In order to get this code to break, instead of passing array[0] as a file name, just pass in an empty string "" and you can reproduce your error.
I have encountered the same problem and was looking for answer. I tried using string.trim() and put it into the outputstream and it worked. I am guessing there are some trailing characters or bits surrounding the file path

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

Ok, so im writing a program that transfers files from my usb to a computer (so i can set up stuff quickly for something im doing on monday) and im trying to make it make a shortcut on the desktop so that you dont have to go into the source folder of the files transfered so you can start up the program again in case you exit it. heres my code, and the title is the error im getting.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Mover {
public static void main(String[] args) throws IOException, InterruptedException {
String usb = new File(".").getAbsolutePath();
String desktop = System.getProperty("user.home") + "/Desktop";
File srcFolder = new File(usb + "/Teamspeak 3");
File destFolder = new File(desktop + "/TS3");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
String cmd = "ls -al";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
while ((line=buf.readLine())!=null) {
System.out.println(line);
Process process = Runtime.getRuntime ().exec (desktop + "/TS3/ts3client_win32.exe");
System.exit(0);
}
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
This line seems malformed. You have two strings without + in between.

Categories

Resources