absolute pathing in java directly to desktop even in different computers [duplicate] - java

This question already has answers here:
How to get the Desktop path in java
(9 answers)
Closed 2 years ago.
How would I be able to automatically direct BufferReader Path to the desktop even in different computer..
'''BufferedReader in = new BufferedReader(new FileReader("C:\Users\.....\ ".txt"));''

You can use
public static void main(String[] args) throws IOException {
String path = System.getProperty("user.home") + "/Desktop/test.txt";
BufferedReader in = new BufferedReader(new FileReader(path));
String line;
while ((line = in.readLine()) != null) {
System.out.println("line = " + line);
}
in.close();
}
To get the desktop path
and read the text file from it

Here’s how I get the desktop directory:
In Windows, I look at the DESKTOP registry entry in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders.
In Linux, I scan the plain text file $XFG_CONFIG_HOME/user-dirs.dirs for a shell-like definition of the XDG_DESKTOP_DIR variable.
On other systems, or if the above fails, fall back on the Desktop directory in the user’s home directory.
My implementation looks like this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.regex.Pattern;
public class DesktopDirectoryLocator {
public static Path getDesktopDirectory()
throws IOException,
InterruptedException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {
String dir = null;
ProcessBuilder builder = new ProcessBuilder("reg.exe", "query",
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
+ "\\Shell Folders", "/v", "DESKTOP");
builder.redirectError(ProcessBuilder.Redirect.INHERIT);
Process regQuery = builder.start();
try (BufferedReader outputReader = new BufferedReader(
new InputStreamReader(regQuery.getInputStream()))) {
String line;
while ((line = outputReader.readLine()) != null) {
if (dir == null) {
String replaced =
line.replaceFirst("^\\s*DESKTOP\\s+REG_SZ\\s+", "");
if (!replaced.equals(line)) {
dir = replaced.trim();
}
}
}
}
int exitCode = regQuery.waitFor();
if (exitCode != 0) {
throw new IOException(
"Command " + builder.command() + " returned " + exitCode);
}
if (dir != null) {
return Paths.get(dir);
}
} else if (os.contains("Linux")) {
// Reference:
// https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
Path configDir;
String configHome = System.getenv("XDG_CONFIG_HOME");
if (configHome != null) {
configDir = Paths.get(configHome);
} else {
configDir = Paths.get(
System.getProperty("user.home"), ".config");
}
Path userDirsFile = configDir.resolve("user-dirs.dirs");
if (Files.isRegularFile(userDirsFile)) {
try (BufferedReader userDirs =
Files.newBufferedReader(userDirsFile)) {
String line;
while ((line = userDirs.readLine()) != null) {
if (line.trim().startsWith("XDG_DESKTOP_DIR=")) {
String value =
line.substring(line.indexOf('=') + 1);
if (value.startsWith("\"") &&
value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
Pattern varPattern = Pattern.compile(
"\\$(\\{[^}]+\\}|[a-zA-Z0-9_]+)");
value = varPattern.matcher(value).replaceAll(r -> {
String varName = r.group(1);
if (varName.startsWith("{")) {
varName = varName.substring(1,
varName.length() - 1);
}
String varValue = System.getenv(varName);
return (varValue != null ?
varValue : r.group());
});
return Paths.get(value);
}
}
}
}
}
return Paths.get(System.getProperty("user.home"), "Desktop");
}
public static void main(String[] args)
throws IOException,
InterruptedException {
System.out.println(getDesktopDirectory());
}
}
To read a file in that directory, you would use:
Path desktopDir = getDesktopDirectory();
Path file = desktopDir.resolve("example.txt");
try (BufferedReader reader = Files.newBufferedReader(file,
Charset.defaultCharset())) {
// ...
}

Related

Not getting Joblog from JES SPOOL using Java

I have written one Java class to submit JCL to Mainframe JES using FTP. The code is able to submit the JCL but it is not retrieving the JOB log from JES SPOOL.
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
public class MVSSpool {
private FTPClient ftp = null;
private String fUserId,fPassword,fHost,fJobPerfix,replyText;
public MVSSpool(String fUserId, String fPassword,
String fHost, String fJobPerfix) {
this.fUserId = fUserId;
this.fPassword = fPassword;
this.fHost = fHost;
this.fJobPerfix = fJobPerfix;
ftp = new FTPClient();
}
public String getfUserId() {
return fUserId;
}
public void setfUserId(String fUserId) {
this.fUserId = fUserId;
}
public void setfPassword(String fPassword) {
this.fPassword = fPassword;
}
public String getfHost() {
return fHost;
}
public void setfHost(String fHost) {
this.fHost = fHost;
}
public String getfJobPerfix() {
return fJobPerfix;
}
public void setfJobPerfix(String fJobPerfix) {
this.fJobPerfix = fJobPerfix;
}
public void submitJobToSpool(String jobName) throws Exception{
if (jobName != null){
connectMVSFtp();
InputStream is = null;
BufferedReader br = null;
String currentLine = null;
try{
ftp.retrieveFileStream("'"+jobName.trim()+"'");
replyText = ftp.getReplyString();
System.out.println("some " + replyText);
String[] replies = ftp.getReplyStrings();
String remoteFileName = replies[replies.length - 1].split(" ")[2]+ ".2";
for(String rep :replies){
System.out.println("checking .. " + rep);
}
Thread.sleep(10000);
System.out.println("getting sysout of the file " + remoteFileName);
is = ftp.retrieveFileStream(remoteFileName);
replies = ftp.getReplyStrings();
for(String rep :replies){
System.out.println("checking 2 .. " + rep);
}
if (is != null){
br = new BufferedReader(new InputStreamReader(is));
while((currentLine = br.readLine()) != null){
System.out.println(currentLine);
}
}
ftp.completePendingCommand();
System.out.println("Done...");
}catch(Exception e){
e.printStackTrace();
throw new Exception("Error in submitting Job from spool");
}finally{
ftp.disconnect();
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}
}
}
/**
* #throws SocketException
* #throws IOException
*/
private void connectMVSFtp() throws SocketException, IOException {
// check if the required parameters are set already
if (fUserId == null | fPassword == null | fHost == null){
}else{
ftp.connect(fHost);
replyText = ftp.getReplyString();
System.out.println(replyText);
// login using user name and password
ftp.login(fUserId, fPassword);
replyText = ftp.getReplyString();
System.out.println(replyText);
// point the FTP to JES spool
ftp.site("filetype=jes");
replyText = ftp.getReplyString();
System.out.println(replyText);
}
}
}
I am getting below messages
230 XXXXX is logged on. Working directory is "XXXXX.".
200 SITE command was accepted
some 125-Submitting job 'XXXXX.XXXX.JCLLIB(ALIAS)' FIXrecfm 80
125 When JOB07591 is done, will retrieve its output
checking .. 125-Submitting job 'XXXXX.XXXX.JCLLIB(ALIAS)' FIXrecfm 80
checking .. 125 When JOB07591 is done, will retrieve its output
getting sysout of the file JOB07591.2
checking 2 .. 550 No spool files available for JOB07591, JesPutGet aborted
Done...enter code here

Java ProcessBuilder Output to String

How to redirect or get the system output to String?
ProcessBuilder pb = new ProcessBuilder().inheritIO();
...
for (...){
pb.command(...);
pb.start();
//here >>> assign output string to variable
}
Here is an opinion on how to capture the standard output of a system command process into a string container.
Adapted from the web:
try {
ProcessBuilder pb = new ProcessBuilder("echo", "dummy io");
final Process p=pb.start();
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!=null) sb.append(line);
}
System.out.println(sb.toString());
In congruence with my original comment on what would be a good example of Basic I/O. I hacked out some code, with a few more features than basic.
Extras
An environment shell for variables and
A working directory
These features add "profile-style" execution to your System commands.
Foundational Work
Java Threading and Joining by Oracle.
Code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Created by triston on 11/2/17.
*/
public class Commander {
private Commander(){} // no construction
public static class StreamHandler implements Runnable {
Object source;
Object destination;
StreamHandler(Object source, Object oDestination) {
this.source = source; this.destination = oDestination;
}
public void run() {
if (source instanceof InputStream) {
BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) source));
String line;
try {
while ((line = br.readLine()) != null) ((StringBuilder) destination).append(line + '\n');
} catch (IOException oE) {
}
} else {
PrintWriter pw = new PrintWriter((OutputStream)destination);
pw.print((String)source);
pw.flush(); pw.close();
}
}
public static Thread read(InputStream source, StringBuilder dest) {
Thread thread = new Thread(new StreamHandler(source, dest));
(thread).start();
return thread;
}
public static Thread write(String source, OutputStream dest) {
Thread thread = new Thread(new StreamHandler(source, dest));
(thread).start();
return thread;
}
}
static Map<String, String> environment = loadEnvironment();
static String workingDirectory = ".";
static Map<String, String> loadEnvironment() {
ProcessBuilder x = new ProcessBuilder();
return x.environment();
}
static public void resetEnvironment() {
environment = loadEnvironment();
workingDirectory = ".";
}
static public void loadEnvirons(HashMap input) {
environment.putAll(input);
}
static public String getEnviron(String name) {
return environment.get(name);
}
static public void setEnviron(String name, String value) {
environment.put(name, value);
}
static public boolean clearEnviron(String name) {
return environment.remove(name) != null;
}
static public boolean setWorkingDirectory(String path) {
File test = new File(path);
if (!test.isDirectory()) return false;
workingDirectory = path;
return true;
}
static public String getWorkingDirectory() {
return workingDirectory;
}
static public class Command {
ProcessBuilder processBuilder = new ProcessBuilder();
Process process;
public Command(String... parameters) {
processBuilder.environment().putAll(environment);
processBuilder.directory(new File(workingDirectory));
processBuilder.command(parameters);
}
public int start(String input, StringBuilder output, StringBuilder error) throws IOException {
// start the process
process = processBuilder.start();
// start the error reader
Thread errorBranch = StreamHandler.read(process.getErrorStream(), error);
// start the output reader
Thread outputBranch = StreamHandler.read(process.getInputStream(), output);
// start the input
Thread inputBranch = StreamHandler.write(input, process.getOutputStream());
int rValue = 254;
try {
inputBranch.join(); rValue--;
outputBranch.join(); rValue--;
errorBranch.join(); rValue--;
return process.waitFor();
} catch (InterruptedException oE) {
oE.printStackTrace();
return rValue;
}
}
}
Testing
#Test public void foo() {
Command cmd = new Command("sh", "--");
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
int pValue = 127;
try {
pValue = cmd.start("echo well done > /dev/stderr\n\necho oh, wow; false", output, error);
} catch (IOException oE) {
}
System.out.println("output: "+output.toString());
System.out.println("error: "+error.toString());
System.out.println("\nExit code: "+pValue);
System.exit(pValue);
}
Bring your own package and JUnit annotations. This sample code demonstrates return value, command input, command standard output, and command error output.
My original design, called for the main thread to perform the standard output processing.
Have a great day.

Why is line from file not printed in java

I'm trying to read a file in java. In that file, some string is given which I want to print. But my code prints only lines of even numbers and skips lines of odd numbers.
I searched for that in stackoverflow, but have found no solution previously answered.
My code is given below...
//main class
import java.io.IOException;
public class takingInputFrpmFile {
public static void main(String[] args) throws IOException {
String filePath = "F:/Path/in.txt";
try
{
readFile rF = new readFile(filePath);
String[] receivedArray = rF.Read();
for(int i=0;i<receivedArray.length;i++)
System.out.println(receivedArray[i]);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
// class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
private String path;
public readFile(String path)
{
this.path=path;
}
public String[] Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
String[] textData = new String[110];
String check;
int i=0;
while((check = bR.readLine()) != null)
{
textData[i] = bR.readLine();
i++;
}
bR.close();
return textData;
}
}
The file contains this lines...
This is the output of my code....
What is wrong with my code? What should I change? How to get rid of printing that last nulls ? Help please... Thanks in advance...
You are first reading the line and checking it's not null, then you read another line.
while((check = bR.readLine()) != null)
{
textData[i] = check; //Changed this to check
i++;
}
That one will work.
You are currently declaring String array which has size of 110. Is your file really 110 line long? You probably should use list instead.
public List<String> Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
List<String> textData = new ArrayList<>();
String check;
while((check = bR.readLine()) != null)
{
textData.add(check);
}
bR.close();
return textData;
}
If you really want to return string array you can use:
return textData.toArray(new String[textData.size()]);
You are reading file lines twice, one when you do
check = bR.readLine()
and other when you do
textData[i] = bR.readLine();
(Each bR.readLine() reads one line)
Try changing your loop for something like
while ((textData[i] = bR.readLine()) != null) {
i++;
}
To get rid of the nulls, you can use a List instead of using a fixed size (110) array.
I suggest the following code:
//main class
import java.io.IOException;
import java.util.List;
public class Prueba {
public static void main(String[] args) throws IOException {
String filePath = "E:/Temp/in.txt";
try {
ReadFile rF = new ReadFile(filePath);
List<String> receivedArray = rF.read();
for (String currentLine : receivedArray) {
System.out.println(currentLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
//class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
private final String path;
public ReadFile(String path) {
this.path = path;
}
public List<String> read() throws IOException {
// Create an empty List to protect against NPE
List<String> textData = new ArrayList<String>();
FileReader fR = null;
BufferedReader bR = null;
try {
fR = new FileReader(path);
bR = new BufferedReader(fR);
String line;
while ((line = bR.readLine()) != null) {
textData.add(line);
}
} catch (IOException e) {
throw e;
} finally {
// Close all the open resources
bR.close();
fR.close();
}
return textData;
}
}
Anyway, as Mukit Chowdhury suggested, please respect code conventions to make your code more readable (you can Google "Java code conventions" or use a well stablished ones)
It seems you do 2 read statements. Try something like:
while((check = bR.readLine()) != null)
{
textData[i] = check;
i++;
}
your line pointer incrementing two times,
while((check = bR.readLine()) != null){
textData[i] = bR.readLine();
i++;
}
Replace bR.readLine() to check in your while loop.
while((check = bR.readLine()) != null){
textData[i] = check ;
i++;
}
You call readline twice. Your loop should read
for(; (check = br.readline()) != null; textdata[i++] = check);
Or something to that effect
In Java 8, reading all lines from a File into a List<String> is easily done using utility classes from the java.nio.file package:
try {
List<String> lines = Files.readAllLines(Paths.get("/path/to/file"));
} catch (IOException e) {
// handle error
}
It's really no longer necessary to use external libraries or to re-invent the wheel for such a common task :)
From your code sample
here
while((check = bR.readLine()) != null) {
textData[i] = bR.readLine();
i++;
}
replace it with
while((check = bR.readLine()) != null) {
textData[i] = check ;
i++;
}

How do I get a file to read into an Arraylist, when the file is opened through a filechooser

I am trying to get a file to read into an Arraylist, then take the numbers read from the file and calculate the average. I am having trouble getting it to read the file and I am opening with a JFileChooser. I have spent three days trying to get this to work. I have seen some similar questions on here but none using a JFileChooser.
Here is my code for the JFileChooser. I know how to calculate the average, but I just need to read the numbers in the file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
fileChooser.showOpenDialog(null);
status = fileChooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
private static double getTheAverage(String theFile) throws NumberFormatException, IOException{
String fileName = getTheFileName();
FileReader fr = new FileReader(theFile);
BufferedReader br = new BufferedReader(fr);
so here is what i have, but now i cant get it to display the average.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser chooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
//theAverage = getTheAverage(theFile);
//displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
chooser.showOpenDialog(null);
status = chooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
public List<String> readFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
//check result
File theFile = chooser.getSelectedFile();
//needs exception handling etc.
BufferedReader br = new BufferedReader(new FileReader(theFile));
List<String> data = new ArrayList<String>();
String line;
while ( (line = br.readLine()) != null)
data.add(line);
br.close();
return data;
}}
public static double average(List<Integer> readFile) {
if (readFile == null || readFile.isEmpty())
return 0.0;
// Calculate the summation of the elements in the list
long sum = 0;
int n = readFile.size();
// Iterating manually is faster than using an enhanced for loop.
for (int i = 0; i < n; i++)
sum += readFile.get(i);
// We don't want to perform an integer division, so the cast is mandatory.
return ((double) sum) / n;
}
}
In Java there is the File class which is used for dealing with, well files. So whether you get the file from a FileChooser or by any other means does not matter.
There are a few things I would do differently in your getTheFileName() methode:
Return the File directly instead of the path
Creating the JFileChooser inside the methode
Check the return value of showOpenDialog (what if the user presses Cancel)
Here is some example code which reads the content of a file in a list of strings:
public List<String> readFile()
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
//check result
File file = chooser.getSelectedFile();
//needs exception handling etc.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String line;
while ( (line = br.readLine()) != null)
data.add(line);
br.close();
return data;
}
If you are using >= Java 7 you can simply use this:
List<String> data = Files.readAllLines(Path path, Charset cs);
Another way would be to use the Scanner class. This would maybe simplify things, since you can directly check and read integer/double values and sum them up.
Let's start with the proper use of the JFileChooser...
JFileChooser#showOpenDiaog returns an int
Returns: the return state of the file chooser on popdown: JFileChooser.CANCEL_OPTION
JFileChooser.APPROVE_OPTION JFileChooser.ERROR_OPTION if an error
occurs or the dialog is dismissed
This is important, as JFileChooser#getSelectedFile may also return null, which would cause your current code...
public static String getTheFileName() {
String status;
fileChooser.showOpenDialog(null);
status = fileChooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
To throw a NullPointerException...
Instead, you should consider using something like...
public static File getTheFileName() {
File file = null;
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
}
return file;
}
The reason for using the actual File object is it carries much more context and functionality the just a String alone.
The next step is to read the file. Depending on which version of Java you are using you could use...
File file = ...;
List<String> values = new ArrayList<String>(25);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();
}
For Java 7 (using try-with-resources) or
File file = ...;
List<String> values = new ArrayList<String>(25);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
}
}
If you are using Java 6 or earlier. The important thing here is to make sure you are properly closing your resources, if you open, you must make every effort to close it.
Check out Basic I/O and How to use File Choosers for more details

Read regex from properties file in java

I have problem reading values like (\+?\s*[0-9]+\s*)+ from properties file in java, because the value , what I get with getProperty() method is (+?s*[0-9]+s*)+.
Escaping of values in properties file is not an option yet.
Any ideas?
I am pretty late to answer this question, but maybe this could help others that end up here.
Newer versions of Java (not sure which, I am using 8) support escaping of values by using \\ to represent the normal \ we are used to.
For example, in your case, (\\+?\\s*[0-9]+\\s*)+ is what you are looking for.
I think this class could be solution for the backslash problem in properties file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class ProperProps {
HashMap<String, String> Values = new HashMap<String, String>();
public ProperProps() {
};
public ProperProps(String filePath) throws java.io.IOException {
load(filePath);
}
public void load(String filePath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().length() == 0 || line.startsWith("#"))
continue;
String key = line.replaceFirst("([^=]+)=(.*)", "$1");
String val = line.replaceFirst("([^=]+)=(.*)", "$2");
Values.put(key, val);
}
reader.close();
}
public String getProperty(String key) {
return Values.get(key);
}
public void printAll() {
for (String key : Values.keySet())
System.out.println(key +"=" + Values.get(key));
}
public static void main(String [] aa) throws IOException {
// example & test
String ptp_fil_nam = "my.prop";
ProperProps pp = new ProperProps(ptp_fil_nam);
pp.printAll();
}
}
Just read using a classical BufferedReader instead:
final URL url = MyClass.class.getResource("/path/to/propertyfile");
// check if URL is null;
String line;
try (
final InputStream in = url.openStream();
final InputStreamReader r
= new InputStreamReader(in, StandardCharsets.UTF_8);
final BufferedReader reader = new BufferedReader(r);
) {
while ((line = reader.readLine()) != null)
// process line
}
Adapt to Java 6 if necessary...

Categories

Resources