I am using java.net.DatagramPacket to trans file. I have some code below
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
String filePath = "e:\\uri\\" + fileName;
System.out.println(filePath);
FileInputStream inputFile = new FileInputStream(filePath);
}
I have a folder uri in and do create file.txt first. While debuging this, this is what shows up in console:
e:\uri\file.txt
java.io.FileNotFoundException: Invalid file path
at java.io.FileInputStream.<init>(FileInputStream.java:133)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at MyFileServerSocket.sendFile(MyFileServerSocket.java:19)
at FiletransServer.main(FiletransServer.java:22)
I found something more interesting that i can see the value of fileName in eclipse and it's strange.
There is extra quotation marks in there and the string printed in the console is normal. No idea why.
I suppose fileName you've passed into sendFile(...) has illegal characters. Please check it thoroughly and you should try hardcode filePath something like this and try once again:
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
// Hardcode file.txt
String filePath = "e:\\uri\\file.txt";
// Print fileName surrounded with quoutes
System.out.printf("'%s'", fileName);
FileInputStream inputFile = new FileInputStream(filePath);
}
Related
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.
Where could I be going wrong?
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //file is at this path.
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
Is there any other way I could read the file?
this code
FileReader inputFile = new FileReader(filename);
You must define full path to file with name filename if not it will open file not at current working directory
you should try
FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
you can read more at: Java, reading a file from current directory?
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources
I create a zip file using below code. Zip is created properly, then later in my program I try to get a zip entry from this file. And if I print a zip entry name I get windows path separators(Eg \a\b\c). But I need this like a/b/c. I have not posted reading zip entry code.
public static void zipFolder(File subdirs, String ZipName) throws FileNotFoundException, IOException {
try (FileOutputStream fileWriter = new FileOutputStream(location+File.seperator+ ZipName);
ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
addFolderToZip(subdirs, subdirs, zip);
}
}
private static void addFileToZip(File rootPath, File srcFile, ZipOutputStream zip) throws FileNotFoundException, IOException {
if (srcFile.isDirectory()) {
addFolderToZip(rootPath, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
try (FileInputStream in = new FileInputStream(srcFile)) {
String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
zip.putNextEntry(new ZipEntry(name));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
}
private static void addFolderToZip(File rootPath, File srcFolder, ZipOutputStream zip) throws FileNotFoundException, IOException {
for (File fileName : srcFolder.listFiles()) {
addFileToZip(rootPath, fileName, zip);
}
}
The root cause of your problem in the following snippet:
String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
zip.putNextEntry(new ZipEntry(name));
The File.getPath() method returns the path with the system-dependent default name-separator.
So, according to this
Within a ZIP file, pathnames use the forward slash / as separator, as required by the ZIP spec (4.4.17.1). This requires a conversion from or to the local file.separator on systems like Windows. The API (ZipEntry) does not take care of the transformation, and the need for the programmer to deal with it is not documented.
you should rewrite this snippet in the following way:
String name = srcFile.getPath();
name = name.replace(rootPath.getPath() + File.separator, "");
if (File.separatorChar != '/') {
name = name.replace('\\', '/');
}
zip.putNextEntry(new ZipEntry(name));
Hi i am running java app from jar file. like following java -cp test.jar com.test.TestMain . in the java app i am reading csv file. which is throwing below exception.
java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
at com.test.TestMain.main(TestMain.java:43)
*csv file is located in src/main/resources folder.
code causes to exception is
public static void main(String[] args) throws Exception {
TestMain trainerScraper = new TestMain();
trainerScraper.run();
}
private void run() throws JsonParseException, JsonMappingException, IOException{
String line = "";
String cvsSplitBy = ",";
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
System.out.println(csvFile);
URL url = classLoader.getResource("us_postal_codes.csv");
String fileName = url.getFile();
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
line = scanner.nextLine(); //header
while ((scanner.hasNextLine())) {
thanks.
test.jar!\us_postal_codes.csv (The filename, directory name, or volume
label syntax is incorrect)
Would suggest using
System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder
and
getResourceAsStream("/us_postal_codes.csv") // if its inside a jar
Based on the stack trace below we can see that the Scanner cannot find the file:
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
By the way, where is the file? If it's in the jar, then you can use TestMain.class.getResourceAsStream() - Scanner has an InputStream constructor too:
InputStream iStream = TestMain.class.getResourceAsStream("/us_postal_codes.csv"); // this supposes the csv is in the root of the jar file
try (Scanner scanner = new Scanner(iStream)) {
//...
}
//...
You should use getResourceAsStream. This is example:
public void test3Columns() throws IOException
{
InputStream is = getClass().getResourceAsStream("3Columns.csv");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
CSVLineTokenizer tok = new CSVLineTokenizer(line);
assertEquals("Should be three columns in each row",3,tok.countTokens());
}
br.close();
isr.close();
is.close();
}
ClassLoader.getResource method is not used to search files in .jar archives.
In the below program, I have to first read a file and then write it. In the run configurations I provided the path of the file but when I run the program then it gives error: String index out of range: -1. ? Please help
public static void main(String[] args) throws IOException{
String fileName = args[0];
Scanner filescan;//to read the file
filescan=new Scanner(new File(fileName));//read the whole file
FileWriter fstream = new FileWriter(fileName.subSequence(0,fileName.indexOf(".uniqe.ICext"))+".uniqe.Mpwm");
BufferedWriter mpwm = new BufferedWriter(fstream);
you should add validations before use substring. otherwise it will eventually throw an Exception
int i= fileName.indexOf(".uniqe.ICext");
if(i<0)
//file name can't substring or handle exception
else
FileWriter fstream = new FileWriter(fileName.subSequence(0,i)+".uniqe.Mpwm");
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