So, basically it works, but it doesn't. It doesn't throw any errors, it just doesn't finish writing the file. It does read all of the lines in the file and they are all formatted correctly. I've tried debugging all of that. When debugging the "currentLine" all of the lines show up and are formatted correctly; However if I check my file that I'm writing to, it writes some of them perfectly, and then will just cut off at the end. Like the program didn't have enough time before killing itself.
My guess would be that writing takes awhile, and the program is being terminated before the file finishes writing, if that's the case, how can I avoid that?
Here's the code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
BufferedReader fileReader;
BufferedWriter fileWriter;
private Main() {
try {
fileReader = new BufferedReader(new FileReader("File/spawn-config.cfg"));
fileWriter = new BufferedWriter(new FileWriter("Dumped/world_npcs.json"));
loadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadFile() {
String currentLine;
try {
fileWriter.write("[\n");
while((currentLine = fileReader.readLine()) != null) {
if(!currentLine.startsWith("//") && !currentLine.startsWith("[")
&& !currentLine.startsWith("/*")) {
System.err.println(currentLine);
String[] array = currentLine.split("\\t");
String npcID = array[0].substring(7);
String xPos = array[1];
String yPos = array[2];
String zPos = array[3];
String walk = "false";
String radius = "0";
//-----------------------
fileWriter.write("{\n");
fileWriter.write("\"npc-id\": "+npcID+"\n");
fileWriter.write("\"position\": {\n");
fileWriter.write("\"x\": " + xPos + "\n");
fileWriter.write("\"y\": " + yPos + "\n");
fileWriter.write("\"z\": " + zPos + "\n");
fileWriter.write("},\n");
fileWriter.write("\"walking-policy\": {\n");
fileWriter.write("\"coordinate\": false, \"radius\": 0\n");
fileWriter.write("}\n},");
}
}
fileWriter.write("]");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] params) {
new Main();
}
}
If you are ready with writing flush and close the outputstream
fileWriter.flush();
fileWriter.close();
Related
I have tried out.append(s); However my problems grow out of control. Anyone else see anything my eyes are missing?
public void writeToFile()
{
PrintWriter out = null;
try
{
out = new PrintWriter(new BufferedWriter(new FileWriter("course.txt", true)));
for (String courseName:courseData.keySet())
{
Course course = courseData.get(courseName);
if (!course.isEmpty())
{
ArrayList<String> students = course.getStudentList();
for (String s : students)
{
out.println(courseName + "<<<<" + s);
}
}
else
{
out.println(courseName + "<<<<");
}
}
} catch (IOException ex)
{
Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
out.close();
}
}
My text file should look like this after I make an entry.
However this is the result I actually get.
//use pw.flush() at the end to avoid multiple copies
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
public class MergeFiles {
public static void main(String[] arg) throws IOException
{
File dir=new File("E:\\videos\\assignments\\fileWork");
File file = new File("E:\\videos\\assignments\\fileWork\\MergeAllAssignments.txt");
file.getParentFile().mkdirs();
PrintWriter pw=new PrintWriter(file);
String[] fileNames=dir.list();
for(String files:fileNames)
{
System.out.println("Reading file "+files);
File f=new File(dir,files);//instance of file to read
BufferedReader br=new BufferedReader(new FileReader(f));//f>>filereader>>bufferedReader
String line=br.readLine();//reading line by line
while(line!=null)
{
System.out.println(line);
pw.println(line);
line=br.readLine();
}
pw.println("\r\n\n\r\n next days assignment>>>>>>>>>>>>>>>>>>>\r\n\r\n\r\n\r\n\r\n");
//to write everything in pw object to destinatio
}
pw.flush();
pw.close();
System.out.println("Copying completed");
}
}
Im creating a java app in which some text is to be stored in a text file. But store function will run in a loop where every cycle will fetch data from other classes and store in the text file. I want that my text file should store data on each cycle just like you create log. here is some piece of code:
public void store(){
File file = new File("PaperRecord.txt");
try{
PrintWriter fout = new PrintWriter(file);
fout.println("Paper Name: " + super.getpSame());
fout.println("Paper Size: " + super.getpSize());
fout.println("Paper Year: " + super.getpYear());
fout.println("Paper Author: " + super.getpAuthor());
fout.println("Paper Description: " + getpDesc());
fout.println("Paper Signature: " + getpSign());
fout.println("Email: " + getPEmail());
fout.println("");
}
catch(FileNotFoundException e){
//do nothing
}
}
Calling store function from main using loop:
while(!q.isEmpty()){
Papers temp = q.remove();
temp.print();
temp.store();
}
THe problem currently with this code is that the code create new file paperrecord each time or overrite existing. I want the same file to be increased and updated downward (more text added)
Files class is your friend dear.
try {
Files.write(Paths.get("PaperRecord.txt"), "new text appended".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Or,a sample working code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample {
private static final String FILENAME = "E:\\test\\PaperRecord.txt";
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String data = " This is new content";
File file = new File(FILENAME);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I'm trying to read/write a .txt file in UTF-16 so that I can input/output Japanese characters into/from my program. I have read many similar questions, articles and the Java Docs, virtually copied their code and still can't figure out where I am going wrong. If I output it to the console, or whenever I check the contents of the file (using the correct encoding) all I see is a '?' in place of 'あ'.
Application class:
public class App {
public static void main(String[] args) {
String[] s = {"あ"}; //A test String array
FileReader.write("unicode.txt", "UTF-16", s, false);
System.out.println("File: " + FileReader.read("unicode.txt", "UTF-16") + " Hard-coded example: あ");
}
}
FileReader class:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.nio.charset.Charset;
public class FileReader {
public static String[] read(String fileName, String encoding) {
ArrayList<String> content = new ArrayList<String>();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.forName(encoding).newDecoder()))) {
for(String s = reader.readLine(); s != null; s = reader.readLine()) {
content.add(s);
}
reader.close();
} catch(IOException e) {
System.out.println("An IOException(Input) has been thrown.");
e.printStackTrace();
}
return convertToStringArray(content);
}
public static void write(String fileName, String encoding, String[] content, boolean append) {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, append), Charset.forName(encoding).newEncoder()))) {
for(String s : content) {
writer.write(s);
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("An IOException(appending=" + append + ") has been thrown.");
e.printStackTrace();
}
}
private static String[] convertToStringArray(ArrayList<String> list) {
String[] array = new String[list.size()];
list.toArray(array);
return array;
}
}
I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}
I would like to run a Dos program from a web server. The Dos program has to be run interactively as the user interface is via a series of questions and answers. The answer to one question will determine the next question. I will have to use ajax on the web server, but I think I can do that.
I found one java program on Stackoverflow which seems to do something similar to what I want. However when I compile the program I get an error ie.
javac PipeRedirection.java
PipeRedirection.java:43: package InputProcess does not exist
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
The stack overflow question url was
How can I write large output to Process getOutputStream?
The Java file was
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Does anyone know why I get the compile error? Can I substitute some other code for InputProcess?
Thanks for any help
Peter
I think it's pretty obvious that you're missing parts to this code. A package named InputProcess which has a class called Gobbler was not included in the OP's post. Probably because it was not relevant to their question.
The error message essentially says that it can not find this package/code that it is looking for.
What this class does exactly, only the OP can tell you. At its most basic, though, it appears to read from an InputStream and convert it to a List<String>. I would read up on Java IO and try to replicate similar functionality.
Edit:
Looks like the Gobbler class is indeed included in the example above. Remove the InputProcess package name from your code (or put the Gobbler class in an InputProcess package) and you should be good to go.