So everything is showing correctly in my Java IDE and runs as it should. I have it where the data automatically writes to the csv file every few minutes. The problem I'm having is that the "Meter 2" column is not showing up and I have a feeling that the HashSet in my code might think that it's a duplicate and deleting it.
Here's the code:
package HourMeter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Hours {
Set<String> hour = new HashSet<>();
String filename;
/**
* #param filename filename of the .csv file to update
* #param addresses Array of Strings of addresses to add to the .csv file
* #throws IOException Throws exception on incorrect filename
*/
public Hours(String filename, String[] addresses) throws IOException {
if(filename==null) throw new IllegalArgumentException();
this.filename = filename;
try (BufferedReader reader = new BufferedReader(new
FileReader("Hours.csv"))) {
while(reader.ready())
{
hour.add(reader.readLine());
}
}
if(addresses != null)
{
hour.addAll(Arrays.asList(addresses));
}
}
Hours(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
public void outputFile() throws IOException
{
try (PrintWriter out = new PrintWriter("Hours.csv")) {
hour.forEach((s) -> {
out.println(s);
});
}
}
}
Below is a photo of the program and the csv report.
As you can see, the csv report is missing a set of string values, meter 2. What should I think about doing or changing in my code to make this show in the csv report? Thanks for the help. I have been trying to figure this out for a few days now. Any help would be greatly appreciated!
Related
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();
}
}
}
I am currently working on a machine learning project. I have a package/directory of java files and i want to read their contents. Later, i will apply other methods to achieve results.
The problem is that the given code reads the txt files, however, when i pass the directory containing java files it doesn't work properly. Following is what I did
I read the names of all files in a directory.
As every directory has different number of files and different structure of files and folders inside it. I am looking for a generic solution.
Next, I read the contents of every file and put it in a list or MAP or whatever
The given code is as follows. I have written 3 methods.
This method list all files in a directory and make a set
// it will list all files in a directory.
public Collection<File> listFileTree(File dir) {
Set<File> fileTree = new HashSet<File>();
for (File entry : dir.listFiles()) {
if (entry.isFile())
fileTree.add(entry);
else
fileTree.addAll(listFileTree(entry));
}
return fileTree;
}
Here using the above method i have tried to read the contents of each file.
File file = new File("C:\\txt_sentoken");// c\\japa..if i use it code only show directory files
Iterator<File> i = Util.listFileTree(file).iterator();
String temp = null;
while(i.hasNext()){
temp = Util.readFile(i.next().getAbsolutePath().toString());
System.out.println(temp);
}
}
This is the readFile method
// using scanner class for reading file contents
public String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
If i pass a directory (in File file = new File("C:\\txt_sentoken");) containing txt files this code works but for java or c++ or other code directories or packages it doesn't.
Can anyone guide me in refining this code? Also if there is any API or generic solution available please share.
Use Java NIO.2 to achieve your goal.
If you need any filtering you can put checks in the FileVisitor.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class Test {
public static void main(String... args) {
try {
System.out.println(readAllFiles("")); // <----- Fill in path
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<Path, List<String>> readAllFiles(String path) throws IOException {
final Map<Path, List<String>> readFiles = new TreeMap<>();
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(file);
readFiles.put(file, Files.readAllLines(file, StandardCharsets.UTF_8));
return FileVisitResult.CONTINUE;
}
});
return readFiles;
}
}
A Java 8 - also sorted - solution would be:
public static Map<Path, List<String>> readAllFiles(String path) throws IOException {
return Files.walk(Paths.get(path)).filter(p -> !Files.isDirectory(p)).collect(Collectors.toMap(k -> k, k -> {
try {
return Files.readAllLines(k);
} catch (IOException e) {
throw new RuntimeException(e);
}
} , (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
} , TreeMap::new));
}
I have one file that is stored in C:/file.txt. The properties file location.properties contains only the path i.e C:/file.txt. I want to read the properties file, get the location , read the file and display everything.
But I am getting fileNotFound exception. Can anybody help me? This is my code:
package com.tcs.fileRead;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadFile {
/**
* #param args
*/
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("location.properties"));
//prop.load(fileIn);
String loc = prop.getProperty("fileLoc");
System.out.println(loc);
BufferedReader buffer;
buffer = new BufferedReader(new FileReader(loc));
String line;
while((line =buffer.readLine())!= null)
{
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the output:
"C:\file.txt"
java.io.FileNotFoundException: "C:\file.txt" (The filename, directory name, or volume label syntax is incorrect.)
at java.io.FileInputStream.<init>(FileInputStream.java:156)
at java.io.FileInputStream.<init>(FileInputStream.java:111)
at java.io.FileReader.<init>(FileReader.java:69)
at com.tcs.fileRead.ReadFile.main(ReadFile.java:29)
You have the path surrounded with quotes in your properties file, so you are trying to open "C:\file.txt" (which is not a valid path) instead of C:\file.txt.
This question already has answers here:
How to get UTF-8 working in Java webapps?
(14 answers)
Closed 2 years ago.
Help fix the encoding in the servlet, it does not display Russian characters in the output.I will be very grateful for answers.
That is servlet code
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
#SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf8");
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
catch (Exception ex) {
}
}
}
}
}
Here is what I have displayed instead of letters
п»ї ршншнщ олрршшш ошгншщ шгшг РѕСЂРѕСЂРіСЂРіСЂ Рто хрень работает СѓСЂР°
You're setting the character encoding on the request instead of the response. Change request.setCharacterEncoding("utf8"); to response.setCharacterEncoding("UTF-8");
Also: if the default character encoding of your system isn't UTF-8, you should explicitly set the encoding when reading from the file. To do that, you'd need to use an FileInputStream
pRes.setContentType("text/html; charset=UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(pRes.getOutputStream(), "UTF8"), true);
use this one i got the exact result :)
Does anyone know of a java library that would allow me to read m3u files to get
the file name and its absolute path as an array ... ?
Clarification: I would like my java program to be able to parse a winamp playlist
file (.M3U) to get the name+path of the mp3 files in the playlist
A quick google search yields Lizzy, which seems to do what you want.
Try my java m3u parser:
Usage:
try{
M3U_Parser mpt = new M3U_Parser();
M3UHolder m3hodler = mpt.parseFile(new File("12397709.m3u"));
for (int n = 0; n < m3hodler.getSize(); n++) {
System.out.println(m3hodler.getName(n));
System.out.println(m3hodler.getUrl(n));
}
}catch(Exception e){
e.printStackTrace():
}
The project is posted here
m3u is a regular text file that can be read line by line. Just remember the lines that start with # are comments. Here is a class I made for this very purpose. This class assumes you want only the files on the computer. If you want files on websites you will have to make some minor edits.
/*
* Written by Edward John Sheehan III
* Used with Permission
*/
package AppPackage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Edward John Sheehan III
*/
public class PlayList {
List<String> mp3;
int next;
public PlayList(File f){
mp3=new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
addMP3(line);
}
} catch (IOException ex) {
System.out.println("error is reading the file");
}
next=-1;
}
private void addMP3(String line){
if(line==null)return;
if(!Character.isUpperCase(line.charAt(0)))return;
if(line.indexOf(":\\")!=1)return;
if(line.indexOf(".mp3", line.length()-4)==-1)return;
mp3.add(line);
}
public String getNext(){
next++;
if(mp3.size()<=next)next=0;
return mp3.get(next);
}
}
Then just call
Playlist = new PlayList(file);