I am getting nothing out in my console from my System.out.println() in the following code:
LinkedList<Element> ls = count(list);
File outFile = new File(args[1]);
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < ls.size(); i++) {
bw.write((int) ls.get(i).data);
System.out.println("Written out " + ls.get(i).data);
}
bw.flush();
bw.close();
Element object is only a class with an int key; and an Object data;
The BufferedWriter is writing out to the file as it should, but my Console in Eclipse doesn't get the System.out.println(); calls. When I run it in debug mode with breakpoint at bw.write() I keep pressing F8 (hotkey to resume), until the BufferedWriter is done, but nothing gets into the Console. Any ideas of why?
First, please don't use the System console for your logging. Second, add a call to flush(). Finally, make sure you add the same cast you used before (or just save it to a variable).
int payload = (int) ls.get(i).data;
bw.write(payload);
System.out.println("Written out " + payload);
// Or,
// System.out.println("Written out " + ((int) ls.get(i).data));
System.out.flush();
Try outputting the variables for the for loop such as the ls.size(), if nothing is being output there then your code isn't being called at all but if it is then you should be able to figure out what is wrong.
since we don't know what is in ls we don't know if it may even be empty
so to help us try putting
System.out.println("List: " + ls);
System.out.println("List size: " + ls.size());
just before the for loop and tell us the outputs.
Related
I am trying to use a text file as a database and I came across a problem. The problem is when I write the user info on the text file, it doesn't write to the next line when I add a second user. It just overwrites the old one. How can I add a writeToNextLine kind of thing?
public void addAdmin(String adminName, String adminSurName, String adminUserName, String adminPassword) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\cemon\\IdeaProjects\\Library\\src\\database\\AdminUserData.txt"));
writer.write(adminName + " " + adminSurName);
writer.newLine();
writer.write(adminUserName + " " + adminPassword);
writer.newLine();
writer.close();
}
Bad idea. How do you know you're not adding a duplicate user?
If you want a simple text file as a database, load the text file into memory on startup, e.g. as a Map<String, User> keyed by adminUserName, and add a new user there. Whenever a value changes, write all the users back to the text file.
That also ensures that (future) operations like "remove user" will work correctly.
Recommend implementing a UserStore class with the suggested Map as a field, to keep the implementation hidden (encapsulated) from the rest of your program.
You want to enable append mode in the FileWriter. This means that when you write a new line, instead of overwriting, it adds another line.
Your code should be:
public void addAdmin(String adminName, String adminSurName, String adminUserName, String adminPassword) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\cemon\\IdeaProjects\\Library\\src\\database\\AdminUserData.txt", true));
writer.write(adminName + " " + adminSurName);
writer.newLine();
writer.write(adminUserName + " " + adminPassword);
writer.newLine();
writer.close();
}
I'm trying to send the output of my program to a text file called results.txt . Here's my attempt
public void writeFile(){
try{
PrintStream r = new PrintStream(new File("Results.txt"));
PrintStream console = System.out;
System.setOut(r);
} catch (FileNotFoundException e){
System.out.println("Cannot write to file");
}
But everytime I run the code and open the file the file is blank. This is what i want to output:
public void characterCount (){
int l = all.length();
int c,i;
char ch,cs;
for (cs = 'a';cs <='z';cs++){
c = 0;
for (i = 0; i < l; i++){
ch = all.charAt(i);
if (cs == ch){
c++;
}
}
if (c!=0){
//THIS LINE IS WHAT I'M TRYING TO PRINT
System.out.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
}
}
}
Where am I going wrong that it keeps creating the file but not writing to it?
(Btw i do have a main method)
use:
PrintWriter writer = new PrintWriter("Results.txt");
writer.print("something something");
don't forget to add:
writer.close();
when you are done!
As you found, System.out IS-A PrintStream and you can create a PrintStream, passing it a File to have it write to that file. This is the beauty of polymorphism --- your code writes to a PrintStream and it doesn't matter what kind it is: console, file, even network connection, or zipped encypted network file.
So instead of messing with System.setOut (usually a bad idea, as it may have unintended side effects; do this only if you absolutely have to (e.g., in some tests)), just pass the PrintStream of your choice to your code:
public void characterCount (PrintStream writeTo) {
// (your code goes here)
writeTo.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
// (rest of your code)
}
Then you call your method as you want:
public static void main(String[] args) throws FileNotFoundException {
new YourClass().characterCount(System.out);
new YourClass().characterCount(new PrintStream(new File("Results.txt")));
}
(Note that I declared that main may throw a FileNotFoundException, as new File("...") can throw that. When that happens, the program will exit with an error message and stack trace. You could also handle it like you did before in writeFile.)
JAVADOC: "A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently."
PrintStream can be used to write to an OutputStream, not directly to a file. So you can use PrintStream to write to a FileOutputStream and then write to the file with that.
If you just want to simply write to a file though, you can use Cans answer easily!
I am writing an application that writes to a text file.
In this text file, at the beginning of each line, is the line number
How do I get the current line number so that I can write it in my file?
I've thought of a simple counter, but when I terminate and restart my project the counter would reset back to 1.
I've tried LineNumberReader, but that keeps on giving me 0.
Is there any way to get the current line number when writing to a file?
Thanks
try {
FileWriter writer = new FileWriter("src\\book_store\\transaction.txt", true);
read = new FileReader("src\\book_store\\transaction.txt");
line = new LineNumberReader(read);
for(int i = 0; i < output.size(); i++) {
line.readLine();
temp = line.getLineNumber() + " " + timeStamp2 + " " + output.get(i) + " " + timeStamp + "\n";
output.set(i, temp);
writer.write(output.get(i));
}
writer.close();
read.close();
line.close();
} catch (IOException ex) {
System.out.println("File not found.");
}
The mistake you are making is that while you are writing to a file through FileWriter, you are trying to read the same file using FileReader.
This could potentially work if you fsynced the file after each line. However, this is not what you really want to do. As you see from the comments, people get confused as you are complicating the problem.
You already have the counter. It’s the i loop variable. You might add +1, if you want to start from 1.
I'm using mencoder to split files and I'd like to turn this into an Object Oriented approach, if possible, using Java or similar, for example. But I'm not sure the best way, so I leave it in the open. Here is what I need:
I have an excel file with start times and end times, and I need to extract out the appropriate clips from a video file. In the terminal (I'm on Mac OS X) I've had success using, for example:
mencoder -ss 0 -endpos 10 MyVideo.avi -oac copy -ovc copy -o Output.avi
Which creates the video Output.avi by clipping the first 10 seconds of the video MyVideo.avi.
But, like I said, I want to make it so that a program reads in from an excel file, and calls this mencoder command multiple times (over 100) for each of the start times and end times.
I know how to read in the excel file in Java, but I'm not sure it is best to call this command from Java. Plus, I'd like to be able to see the output of mencoder (because it prints out a nice percentage so you know about how much longer a single command will take). Is this type of thing feasible to do in a shell script? I would really like to use Java if possible, since I have many years of experience in Java and no experience in shell scripting.
UPDATE
Here is what I've tried in Java, but it freezes at in.readLine()
File wd = new File("/bin");
System.out.println(wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
}
catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd ..");
out.println("pwd");
String video = "/Users/MyFolder/MyFile.avi";
String output = "/Users/MyFolder/output.avi";
int start = 0;
int end = 6;
String cmd = "mencoder -ss " + start +
" -endpos " + end +
" " + video + " -oac copy -ovc copy -o " + output;
out.println(cmd);
try {
String line;
System.out.println("top");
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.println("end");
proc.waitFor();
in.close();
out.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
I'm not quite sure about mencoders multicore-capabilities, but I think with Java you can use Multiple Threads to get the maximal power of all cpu-cores.
You shouldn't use Runtime like your using it.
When using Runtime, you should not run bash and send commands via inputstream like when you are typing commands on a terminal.
Runtime.getRuntime().exec("mencoder -ss " + start +
" -endpos " + end +
" " + video + " -oac copy -ovc copy -o " + output);
To get the Output, you can use the inputStream
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String[],%20java.io.File%29
With this command you can also set the Workingdirectory where your command is executed.
I also prefer the version with the String[] as parameters. It's much more readable, than the a concatenated String.
ok, so i have this set of code
if(message.toLowerCase().startsWith("!dl.exec")){
String[] args = message.split(" ");
sendMessage(channel, sender +": OK, please wait a moment");
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL(args[1]).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(args[2]);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
int count;
while( (count = in.read(data,0,1024)) != -1){
bout.write(data,0,count);
}
fos.flush();
fos.close();
String absolutePath = new File("").getAbsolutePath()+"/"+args[2];
sendMessage(channel, sender +": the path is " +absolutePath);
Runtime.getRuntime().exec(absolutePath);
}
catch(Exception e){
}
}
and basically what it does is, the user enters !dl.exec (url) (filename) and the thing downloads it and saves it as (filename) then goes to execute it.
now this works fine, but only if the file is a .exe, for .anything else (like.jar) it does not work.
what do i need to change to get it to work with preferably all extensions?
Runtime.getRuntime().exec(String) will execute the command as if launched from a shell. If you are looking to launch a .jar file, use Runtime.getRuntime().exec("java -jar " + absolutePath). You may also need to provide the full path to the java executable from inside the exec(String) method.
You would need to explicitly specify execution behavior of non-standard file types (executables or batch files)