Program catches FileNotFoundException even though the file is in the correct directory - filenotfoundexception

I am writing a program for my CS class and I have to read the text from the data.txt file and if, for whatever reason that file is not there, I am supposed to throw an IOE exception and print out "File not found".
try{
Scanner in = new Scanner(new File("data.txt"));
String temp;
int n = 0;
...
and
catch(FileNotFoundException e){
System.out.println("File not found");
}
but when I run the program, all I get is the "File not found" but the data.txt file is in that folder along with the java program file. Can anyone please help me with how I can make the program see the data.txt file

Related

jcraft execute shell command returns exit status 127

I am trying to run shell script
(/sasdata/sasconfig/Lev1/Applications/SASEnterpriseGRCAdminTools/6.1/dbscripts/addxlsdata.sh -t /sasdata/Data/Loaders/IFT_tst_loader2.xls)
on remote server with java, using jcraft, but in answer I have exit status 127. I tried to run simple command "date" with my method - and all was good. Then I tried to run this script by entering command in terminal, and all was ok too. Also I tried to execute "cd" to path with addxlsdata.sh and there run
./addxlsdata.sh -t /sasdata/Data/Loaders/IFT_tst_loader2.xls
and again there was 127 exit status.
What the problem it can be?
Here is my method:
public static void executeShell(String shellScriptCommand, String userName, String password, String server) {
List<String> result = new ArrayList<String>();
try {
LOG.info("Creating session, user: " + userName);
JSch jSch = new JSch();
Session session = jSch.getSession(userName, server, sshPort);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
LOG.info("Opening exec channel");
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
LOG.info("Creating InputStream");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("sh " + shellScriptCommand);
LOG.info("Executing the shell script: " + shellScriptCommand);
channelExec.connect();
LOG.info("Reading the output from the input stream");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
CommonFunctions.freeze(3);
while (reader.ready()) {
String line = reader.readLine();
result.add(line);
}
reader.close();
LOG.info("OUTPUT is " + result);
LOG.info("Getting exit status");
int exitStatus = channelExec.getExitStatus();
LOG.info("Exit status is [" + exitStatus + "]");
channelExec.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
LOG.error(Arrays.toString(e.getStackTrace()));
throw new AutotestError("Ошибка при выпонении shell скрипта", e);
}
}
I find out one thing. This *.sh file have another script inside "./runjava.sh". Maybe here is the problem
It seems that it is my fault in connect to wrong server. Despite that I use the same address in java and winscp, when I use ls in directory with the script in java and in terminal, I have different results
I think that I have found what the problem. When I execute "cd /" in java and then "pwd", the output is "/home/username". I can't exit from Home directory to root in java. In terminal I can do this with the same user
Your java application has not permission to execute the script. Add the account (which run your java application) to the group which has ownership to script ./addxlsdata.sh. Also provide necessary execute permission as well.
First go to the directory and execute ls -ltr and provide the detail information to your Unix admin and also provide the user id detail which run the java application to add that user to the proper group. It will work once you short out this.
It was my terrible fault. I invoked my method several times with different commands. I was running executeShell "cd /" and then executeShell "pwd". And of course second time it was a new session.

Get permission denied message when creating a file to /var/log on os x

I want to write qt application log to /var/log/message_app.log on OS X. I am getting
"Cannot open file for writing: "Permission denied""
message on console.
This is the my test code parts:
logfile = fopen(logFilePath, "a");
if (!logfile) {
fprintf(stderr, "ERROR: Unable to access keystroke log file. Please make sure you have the correct permissions.\n");
}
and
QString filename = "/var/log/data.txt";
QFile file(filename);
file.setPermissions(QFile::ExeGroup);
file.setPermissions(QFile::ExeOther);
file.setPermissions(QFile::ExeOwner);
file.setPermissions(QFile::ExeUser);
if (!file.open(QIODevice::ReadWrite)) {
qDebug() << "Cannot open file for writing: " << file.errorString();
return 0;
}
else {
QTextStream stream(&file);
stream << "something" << endl;
}
Both of them return same error.
When I start QtCreator from console using sudo command, it works. But when I deployed my app and change some permissions (with chown, chmod, etc.) it doesn't work.
I googled and found out some privileged issues like that.
So, is there any other effective solution?
Thanks!

In C# VS2013 how do you read a resource txt file one line at a time?

static void Starter(ref int[,] grid)
{
StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(Resources.Sudoku));
string line = reader.ReadLine();
Console.Write(line);
Console.ReadLine();
}
I know this isn't right, but it gets my point across.
I would like to be able to read in the resource file one line at a time.
Like so:
System.IO.StreamReader StringFromTxt
= new System.IO.StreamReader(path);
string line = StringFromTxt.ReadLine();
I do not necessarily have to read in from the resource, but I am not sure of any other way to call a text file without knowing the directory every time, or hard coding it. I can't have the user pick files.
StreamReader sr = new StreamReader("D:\\CountryCodew.txt");
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
}
MSDN lists the following as the way to read in one line at a time:
https://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx
int counter = 0; //keep track of #lines read
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
Additional examples for getline:
https://msdn.microsoft.com/en-us/library/2whx1zkx.aspx

D: executeShell on Windows to run another program not returning immediately

I'm using D as a scripting language for Windows 7 console stuff to automate boring tasks. One of my scripts (open.exe) is supposed to allow me to open stuff from the command line without me having to specify which program I use (I have a configuration file with this stuff). Now, I use executeShell to do this, and call something like start [name of program I want to use] [name of input file]. If I do this directly from the shell, it returns immediately, but if I do it using my D script, it doesn't return until the program that it opens is closed. What should I do to allow it to return immediately?
For reference purposes, this is the business logic of my script (the main method just does some argument parsing for piping purposes):
immutable path = "some//path//going//to//config//file.conf";
void process(string input) {
string extension = split(input,".")[1]; //get file extension from input
auto config = File(path,"r"); auto found = false;
while (!config.eof()){
auto line = chomp(config.readln());
if (line[0]!='#') { //skip comment lines
auto divided = split(line, ":");
if (divided[0] == extension) {
found = true;
auto command = "start " ~ divided[1] ~ " " ~ input;
auto result = executeShell(command);
//test for error code and output if necessary
writeln(result.output);
}
}
}
if (!found)
writeln("ERROR: Don't know how to open " ~ input);
}
From the top of the std.process documentation:
Execute and wait for completion, collect output - executeShell
The Windows start program spawns a process and exits immediately. D's executeShell does something else. If you'd like to spawn another program, use the appropriate functions: spawnProcess or spawnShell.

Calling any file/script with Russian name from VBScript fails

I am reading a name of the file/script from an utf-8 encoded XML file. This is then passed to VBScript. VBScript starts a second program to which this passed program/script is provided as an argument. When the argument is in English, the VBScript executes successfully.
But if the name read from XML is non-english( Russian in my case ), VBScript fails to find that file.
I am running VBScript from Java code only using "cscript" as I am running it on Windows.
However, if I copy the command fired by Java program to run VBScript, and paste it on command prompt, it executes normally despite the argument name is in non-english language.
I then hardcoded file/script name in VBScript. Changed encoding of VBScript to UCS2-LE, and directly run it from command prompt. It executed normally. It failed to execute for any other encoding used for VBScript. Also the non-english text is displayed as ? in any other encoding than UCS2-LE.
Then I tried to encode file/script name into UTF16-LE in Java and then passed it to VBScript. Irrespective of which encoding was used in VBScript, it fails. Again if I copy the command printed on standard output from Java program and run it from cmd, it executes.
The command printed from Java displays non-english text correctly.
Can anyone please help me to resolve the issue?
Any relative help would be greatly appreciated.
This is what I am doing currently. I need to pass an argument contatining Russian Text to VBScript from Java.
I tried to use two different approaches.
First approach in the code below writes the Russian text in a file using encoding UnicodeLittle. File is found to be in encoding UCS-2LE. And then VBScript reads the value from that file, and script is executed successfully.
In second approach, I tried to directly pass encoded Russian text as argument to script. VbScript fails saying that script can't be opened.This is the approach I want solution for.
Below is the Java code attached.
Any help would be greatly appreciated.
public class CallProgram
{
private static String encodeType = "UnicodeLittle";
private File scriptName = new File( "F:\\Trial Files\\scriptName.txt" );
public static void main(String[] args)
{
CallProgram obj = new CallProgram();
Runtime rt = Runtime.getRuntime();
try
{
**//Approach1 - Writes text to file and calls vbscript which reads text from file and uses it as an argument to a program**
String sName = "D:\\CheckPoints_SCRIPTS\\Менеджер по качеству"; //Russian Text
byte [] encodedByte= sName.getBytes( encodeType );
String testCase = new String( encodedByte, encodeType ); //New string containing russian text in UnicodeLittle encoding...
obj.writeToFile( testCase ); //Writing russian string to file...
String mainStr = "cscript /nologo \"D:\\Program Files\\2.0.1.3\\Adapter\\bin\\scriptRunner_FileRead_Write.vbs\"";
Process proc1 = rt.exec( mainStr );
int exit = proc1.waitFor();
System.out.println( "Exit Value = " + exit );
**//Approach 2 - Passing encoded Russian text directly to VbScript...**
//This is not working for me...
String [] arrArgs = { "cscript", "/nologo", "\"D:\\Program Files\\IBM\\Rational Adapters\\2.0.1.3\\QTPAdapter\\bin\\scriptRunner.vbs\"", testcase };
ProcessBuilder process = new ProcessBuilder( arrArgs );
Process proc2 = process.start();
proc2.waitFor();
}
catch (IOException e)
{
e.printStackTrace();
}
catch ( InterruptedException intue )
{
intue.printStackTrace();
}
}
//Function to write Russian text to file using encoding UnicodeLittle...
private void writeToFile( String testCase )
{
FileOutputStream fos = null;
Writer out = null;
try
{
fos = new FileOutputStream( this.scriptName );
out = new OutputStreamWriter( fos, encodeType );
out.write( testCase );
out.close();
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch ( IOException ioe )
{
ioe.printStackTrace();
}
finally
{
try
{
if ( fos != null )
{
fos.close();
fos = null;
}
if ( out != null)
{
out.close();
out = null;
}
}
catch( IOException ioe )
{
fos = null;
out = null;
}
}
} // End of method writeToFile....
}
I've resolved similar problems before by using the short 8.3-style filename instead of the long filename. I get this short name using the ShortPath method of FileSystemObject. Here's a VBScript example... you may want to try something similar in Java.
Function GetShortPath(strLongPath)
Dim FSO
Dim objFolder
Dim objFile
Dim strShortPath
Set FSO = CreateObject("Scripting.FileSystemObject")
' Is it a file or a folder?
If FSO.FolderExists(strLongPath) Then
' It's a folder.
Set objFolder = FSO.GetFolder(strLongPath)
strShortPath = objFolder.ShortPath
ElseIf FSO.FileExists(strLongPath) Then
' It's a file.
Set objFile = FSO.GetFile(strLongPath)
strShortPath = objFile.ShortPath
Else
' File not found.
strShortPath = ""
End If
GetShortPath = strShortPath
End Function
For example,
Debug.Print GetShortPath("C:\öêåéèüø.çõâ")
returns C:\B373~1, which can be used in place of the long filename with non-English characters. Example with dir /x (reveals the short filename) and notepad:
C:\sandbox>dir /x
Volume in drive C has no label.
Volume Serial Number is BC90-DF37
Directory of C:\sandbox
13/01/2011 15:12 <DIR> .
13/01/2011 15:12 <DIR> ..
13/01/2011 14:52 22 NEWTEX~1.TXT New Text Document.txt
13/01/2011 15:05 0 C7F0~1.TXT öêåéèüø.txt
13/01/2011 15:05 0 B373~1 öêåéèüø.çõâ
3 File(s) 22 bytes
2 Dir(s) 342,158,913,536 bytes free
C:\sandbox>notepad B373~1

Resources