Paths.get doesnt find file Windows 10 (java) - java

I'm following some course on udemy . Im learning about Paths , but i cant get Paths.get to work.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path filePath = Paths.get("C:\\OutThere.txt");
printFile(filePath);
}
private static void printFile(Path path){
try(BufferedReader fileReader = Files.newBufferedReader(path)){
String line;
while((line = fileReader.readLine())!=null){
System.out.println(line);
}
}catch(IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
The File exists , the name is correct and its on the C drive. What am i doing wrong?
java.nio.file.NoSuchFileException: C:\OutThere.txt
at com.bennydelathouwer.Main.main(Main.java:16)

It's a bad practice to hard-code "/" or "\" use:
File.separator
++ are you sure you have the proper privileges to read this file?

Related

Parse .prn file to html

I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)

It seems my IntelliJ cannot find my csv file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So ive made a class to keep track of the data i've imported:
package com.company;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException{
String file = "Users/mathiaspoulsen/Desktop/SP3MarioPizza/pizzas.csv";
ArrayList <Pizza> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while ((line = br.readLine()) != null) {
line = br.readLine();
String [] lineArr = line.split(",");
Pizza pizza = new Pizza (Integer.parseInt(lineArr[0]),lineArr[1],Double.parseDouble(lineArr[2]));
content.add(pizza);
}
} catch (FileNotFoundException e) {
//Some error logging
}
return content;
}
I have then tried to run it in the main method to see if it loads the csv-file corectly. Like this:
package com.company;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
/* int i = 0;
String fileName = "pizzas.csv";
Path pathToFile = Paths.get(fileName);
System.out.println(pathToFile.toAbsolutePath());
*/
// ArrayList<Pizza> pizzas = ImportData.readData();
System.out.println(ImportData.readData());
}
}
The output of this program is: []
Why dont it display the pizzas? The pizzas in the csv-file a structured like this:
PizzaNumber(int),PizzaName(String), price(double)
1,MARGHERITA,69.00
You read the line multiple times which most likely was causing your issue just read the line once and check to make sure it is not null in the while statement before parsing it. Also, it would be better to check to make sure the parse is successful.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException {
String file = "/Users/your/path/pizza.csv";
ArrayList<Pizza> content = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] lineArr = line.split(",");
content.add(new Pizza(Integer.parseInt(lineArr[0]), lineArr[1], Double.parseDouble(lineArr[2])));
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
return content;
}
}

List attached devices on ubuntu in java

I'm a little stumped, currently I am trying to list all of the attached devices on my system in linux through a small java app (similar to gparted) I'm working on, my end goal is to get the path to the device so I can format it in my application and perform other actions such as labels, partitioning, etc.
I currently have the following returning the "system root" which on windows will get the appropriate drive (Ex: "C:/ D:/ ...") but on Linux it returns "/" since that is its technical root. I was hoping to get the path to the device (Ex: "/dev/sda /dev/sdb ...") in an array.
What I'm using now
import java.io.File;
class ListAttachedDevices{
public static void main(String[] args) {
File[] paths;
paths = File.listRoots();
for(File path:paths) {
System.out.println(path);
}
}
}
Any help or guidance would be much appreciated, I'm relatively new to SO and I hope this is enough information to cover everything.
Thank you in advance for any help/criticism!
EDIT:
Using part of Phillip's suggestion I have updated my code to the following, the only problem I am having now is detecting if the selected file is related to the linux install (not safe to perform actions on) or an attached drive (safe to perform actions on)
import java.io.File;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import javax.swing.filechooser.FileSystemView;
class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> dev = new ArrayList<File>();
for (FileStore store : FileSystems.getDefault().getFileStores()) {
String text = store.toString();
String match = "(";
int position = text.indexOf(match);
if(text.substring(position, position + 5).equals("(/dev")){
if(text.substring(position, position + 7).equals("(/dev/s")){
String drivePath = text.substring( position + 1, text.length() - 1);
File drive = new File(drivePath);
dev.add(drive);
FileSystemView fsv = FileSystemView.getFileSystemView();
System.out.println("is (" + drive.getAbsolutePath() + ") root: " + fsv.isFileSystemRoot(drive));
}
}
}
}
}
EDIT 2:
Disregard previous edit, I did not realize this did not detect drives that are not already formatted
Following Elliott Frisch's suggestion to use /proc/partitions I've come up with the following answer. (Be warned this also lists bootable/system drives)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
class ListAttachedDevices{
public static void main(String[] args) throws IOException {
ArrayList<File> drives = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader("/proc/partitions"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
String text = line;
String drivePath;
if(text.contains("sd")){
int position = text.indexOf("sd");
drivePath = "/dev/" + text.substring(position);
File drive = new File(drivePath);
drives.add(drive);
System.out.println(drive.getAbsolutePath());
}
line = br.readLine();
}
} catch(IOException e){
Logger.getLogger(ListAttachedDevices.class.getName()).log(Level.SEVERE, null, e);
}
finally {
br.close();
}
}
}

Update/Edit property file

I am testing a library (jar) that is using property (mytest.properties). They way the library (jar) loads the property is by doing
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
So what I want to test is what happens when the property file exist and when it does not exit. In order to test this I need to edit the property file once the JVM is started. I have tried doing that and does not work. Bellow is the code I tried to edit the property file but this always returns empty string.
Content of main_mytest.properties is:
a=hello world
b=hello java
Content of mytest.properties and empty.txt is empty.
""
My Class is:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class MyPropertyFiles {
final static String resourcesPath = "./mytestproj/src/main/resources";
public static void main(String [] args) throws IOException {
Path source = Paths.get(resourcesPath + "/main_mytest.properties");
Path destination = Paths.get(resourcesPath + "/mytest.properties");
Path empty = Paths.get(resourcesPath + "/empty.txt");
try
{
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "utf-8");
String theString = writer.toString();
System.out.println("!!!!!!!!!!!!!!!! The String: \n" + theString);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
Files.copy(empty, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
}
After doing some digging I don't think reloading the files in the ClassLoader after the JVM has started is allowed.

Error on finding file and on the New File location

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
fin.close();
}
}
Around the Scanner portion I cant seem to fix the error.
It says File cant be resolved to a type.
And the file cant be found.
You are missing an import java.io.File; statement. Since you did not import this class (and since your code is not located in the java.io package), Java can't recognize it.
You have a type in your code. You code should be:
FileReader fin = new FileReader(new File("running.txt"));
^^^^^^^^^^^^^^
You can't store instance of File within FileReader.
Also the error that you see is because you have not imported java.io.File, so you need to import File like:
import java.io.File;
A side note: You will need to handle FileNotFoundException.
Try importing java.io.File, and change your FileReader line to the following:
FileReader fin = new FileReader(new File("running.txt"));
It compiled fine for me.
Use the following code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
try{
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
}catch(Exception e){}finally{fin.close();}
}
}

Categories