I have had two years experience in Java but have not touched in a year therefore a little rusty.
I am trying to reading a text file line by line using Java8 (the new way).
Based on a forum I have read I am using the following code:
package codeTest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String filename = "RouterInfo.txt";
try(Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(System.out::println);
} catch(IOException e) {
e.printStackTrace();
}
}
}
But no matter what I try I keep getting a java.nio.file.NoSuchFileException.
Here is a picture of my file directory in eclipse:
Can anybody help?
Your text file is in src/codeTest folder so it should be
"src/codeTest/RouterInfo.txt"
Your Java code is correct. Only your RouterInfo.txt is in the wrong place. Just put it into your project directory instead of into src.
Replace filename string with "./src/RounterInfo.txt".
The text file should not be put in the src folder but in the folder that contains src.
Therefore the new folder path should be:
Answer/sample.txt
Answer would be the name of the folder containing src.
Related
I'm working on a very simple project that's supposed to open an image with the windows video player when run. However, I've encountered a problem. I want to have it be able to access the file "snp.jpg" with a relative file path, so it will work on computers other than my own. But, when I have it set to a absolute file path, it fails and tells me that "the file ... does not exist". Any Ideas?
import java.awt.Desktop;
import java.io.File;
public class openpic {
public static void main (String args[]) throws Exception
{
File f = new File ("C:\Users\charl\Desktop\Computer Science\JavaProjects\src\snp.png");
Desktop d = Desktop.getDesktop();
d.open(f);
System.out.println("imageviewer open;");
}
}
(Ops... fixing the answer, after I read the text above the code)
The relative path will start from the directory you run the program. Also called current working directory.
Also, as you are using Files, try to use the NIO API, with Path. Like:
Path filePath = Paths.get("./snp.png")
With this API, you can check the working directory using:
filePath.toAbsolutePath()
// just print it then, or check with a debugger
Also, be careful about the slashes.
When using Windows and this slash \, you need to make them double: \\.
Other option is to invert it: /.
Microsoft Windows syntax
import java.awt.Desktop;
import java.io.File;
public class openpic {
public static void main (String args[]) throws Exception
{
// Microsoft Windows syntax
File f = new File ("C:\\Users\\charl\\Desktop\\Computer Science\\JavaProjects\\src\\snp.png");
Desktop d = Desktop.getDesktop();
d.open(f);
System.out.println("imageviewer open;");
}
}
I am trying to get a java based macro I use to combine all of the .csv files it spits out into one, and the only way I know how to do that is to open up cmd and manually paste in the folder directory. I know almost nothing about java and pretty little about programming in general, and the person who make the macro i use is in a different country rn so i cant ask him for help.
It takes forever to paste all of the results into one csv, and while using cmd is easier it would be nice if I could just have the macro do it for me. That said, I wanted to ask if it is at all possible to even do that?
Any help would be appreciated! If possible, I would also like to get the macro to automatically combine the headings for the csv files.
Also also, the macro has a dialogue box come up that then leads to you selecting the file directory. is it possible to have the cmd command reference the directory already defined by the macro?
java based macro meaning like 20 lines of text written in java... idk i'm a biochemist not a programer. I'm doin my best.
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CSV {
public static void main(String[] args) throws IOException {
List<Path> paths = Arrays.asList(Paths.get("csv1.csv"), Paths.get("csv2.csv"));
List<String> mergedLines = getMergedLines(paths);
Path target = Paths.get("mergecsv.csv");
Files.write(target, mergedLines, Charset.forName("UTF-8"));
}
private static List<String> getMergedLines(List<Path> paths) throws IOException {
List<String> mergedLines = new ArrayList<> ();
for (Path p : paths){
List<String> lines = Files.readAllLines(p, Charset.forName("UTF-8"));
if (!lines.isEmpty()) {
if (mergedLines.isEmpty()) {
mergedLines.add(lines.get(0)); //add header only once
}
mergedLines.addAll(lines.subList(1, lines.size()));
}
}
return mergedLines;
}
}
File1
header1,header2,header3
one,two,three
four,five,six
File2
header1,header2,header3
seven,eight,nine
ten,eleven,twelve
Result
header1,header2,header3
one,two,three
four,five,six
seven,eight,nine
ten,eleven,twelve
To compile the program
javac CSV.java
To run the program
java CSV
I am using Java to create a file with some data in it. But I encouter a problem. Indeed I succeed in creating a file and write "hello" in it when I run from Eclipse. But when I export that code in a jar file and I tried to execute it in the command line (java -jar myappli.jar), the file is not created. I don't understand why.
Here is my java file which is quite simply.
If you have any answers I would be happy to have it :)
Thank you.
package testjar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Main {
public static void main(String[] args)
{
FileOutputStream f = null;
try
{
f = new FileOutputStream(new File("Export_XML.xml"));
System.setOut(new PrintStream(f));
System.out.println("hello");
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(f!=null)
f.close();
}
catch(IOException e) {e.printStackTrace();}
}
}
}
If you're not getting exceptions, it is most likely being created. The difference is the working directory. Since you're not specifying an absolute path when calling new File the JVM will create the file in the current working directory for the JVM. This is likely different when you're running from the jar vs where it is when you run from Eclipse.
I cannot see what is specifically wrong, but try making the new File('Export_XML.xml') into its own variable, then doing xmlFile.createNewFile(); Also, I discourage the use of System.setOut() as your program isn't the only part of Java to use it.
I have the following code for reading a excel sheet in Java using the Apache POI. Although the file exists, why does it give me a FileNotFound Exception?
import org.apache.poi.hssf.usermodel.HSSFSheet;
import java.io.FileInputStream;
import java.io.File;
public class ReadFromExcel {
public static void main(String[] args) {
FileInputStream file = new FileInputStream(new File("C:\\Personal\\test.xlsx"));
}
}
I just copied and pasted the File location from windows explorer so I know that the file exists for sure. Then Why can't Java find it?
Used same path with the "File" class instead of "FileInputStream" and it works fine. What is special about paths in the class FileInputStream?
Try this code:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadFromExcel {
public static void main(String[] args) throws FileNotFoundException {
File f=new File("C:"+File.separator+"Personal"+File.separator+"test.xlsx");
FileInputStream file=null;
if(f.exists()) {
file = new FileInputStream(f);
//rest of code
} else{
System.out.println("The file does not exist!Please enter correct filename!");
}
}
}
I have 3 things to point out:
Firstly you have not added a try/catch block.My IDE simply does not let it compile!
Using File.separator is the more recommended way instead of using "\" or "/" if you are using file paths as they depend on OS.They make your code more portable.
Checking that the file whether exists or not using f.exists() would let you know if actually the file you are trying to pass as parameter to FileInputStream exists.
Sure that would help!!
Maybe the first two '\' only represent one '\', so you can use file path as "C:\\Personal\test.xlsx"
Suggestion: call File.canRead() to see if you have permissions to open the file.
Java new File() says FileNotFoundException but file exists
There are three cases where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.