How to write it to a file?
I need some help with the following code. I think I understand what is happening, but I just don't know what to do to change it. I am attempting to 1.Open a .txt File and read its contents using a BufferedReader. 2. Create two HashSets - one to hold the unique strings from the file and another to hold the duplicate strings from the file. 3.Iterate through each line of the file and if it is NOT unique, add it to the duplicate HashSet, if it IS unique, do nothing withit. 5. Remove the duplicates from the uniques HashSet and print out to a .txt file (using BufferedWriter)the balance of what is left (which should be just the unique strings.)
Here is the code:
import java.util.*;
import java.io.*;
public class WriteToDups2
{ // Open Class WriteToDups2
public static void main(String[] args)
{ // Open Main
// Read words from file
try { // Open Outer Try
BufferedReader in = new BufferedReader(new FileReader("Pal_out2.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("Palslm.txt"));
Set dups = new HashSet();
String str;
while ((str = in.readLine()) != null)
{ // Open While
Set uniques = new HashSet();
for (int i=0; i<args.length; i++)
{ // Open For
if (!uniques.add(args))
{// Open IF
dups.add(args[i]);
}// Close IF
//uniques.removeAll(dups); //Destructive set-difference
Set uniques2 = new HashSet(uniques); // Non-Destructive set-difference
uniques2.removeAll(dups); // Non-Destructive set-difference
} // Close FOR
try {//Open Inner Try
out.write(uniques2);
}catch (IOException e) // Close Inner Try
{ // Open Inner Catch
} // Close Inner Catch
}//Close WHILE
out.close();
in.close();
} catch (IOException e) // Close Outer Try
{ // Open Outer Catch
} // Close Outer Catch
}//Close Main
}//Close Class WriteToDups2
What am I doing wrong? The error message I get when compiling is as follows:
D:\jsdk14102\WriteToDups2.java:46: cannot resolve symbol
symbol : variable uniques2
location: class WriteToDups2
out.write(uniques2);Please help!!
Thanks in advance...
Ok...I moved the HashSet declarations to the beginning of the code. But I still get the following error:
D:\jsdk14102\WriteToDups2.java:45: cannot resolve symbol
symbol : method write (java.util.HashSet)
location: class java.io.BufferedWriter
out.write(uniques2);Here is how I changed the code:
import java.util.*;
import java.io.*;
public class WriteToDups2
{ // Open Class WriteToDups2
public static void main(String[] args)
{ // Open Main
HashSet uniques = new HashSet(), uniques2 = new HashSet();
// Read words from file
try { // Open Outer Try
BufferedReader in = new BufferedReader(new FileReader("Pal_out2.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("Palslm.txt"));
Set dups = new HashSet();
String str;
while ((str = in.readLine()) != null)
{ // Open While
//Set uniques = new HashSet();
for (int i=0; i<args.length; i++)
{ // Open For
if (!uniques.add(args))
{// Open IF
dups.add(args[i]);
}// Close IF
//uniques.removeAll(dups); //Destructive set-difference
//Set uniques2 = new HashSet(uniques); // Non-Destructive set-difference
uniques2.removeAll(dups); // Non-Destructive set-difference
} // Close FOR
try {//Open Inner Try
out.write(uniques2);
}catch (IOException e) // Close Inner Try
{ // Open Inner Catch
} // Close Inner Catch
}//Close WHILE
out.close();
in.close();
} catch (IOException e) // Close Outer Try
{ // Open Outer Catch
} // Close Outer Catch
}//Close Main
}//Close Class WriteToDups2
I think there is something wrong with the way I am attempting to write it out to the new file. What do you think?
Similar Messages
-
How to write to a log file within a JSP
Hello everybody,
do you know how to write to a log file within a JSP.
my code is (/space/SP/tlf/ExcepcionJava.jsp):
<html>
<body bgColor=#C4E1FF>
<%@ page import="java.io.*" %>
<%
FileWriter salida = new FileWriter(response.encodeURL("log.txt"));
salida.write(request.getParameter("errorMsg"));
salida.close();
%>
</body>
</html>.. I run under Solaris, Jrun 2.3.3
I have also test with getServletContext().getRealPath(), but I get /netsrv/nes/docs/ instead of /space/SP/tlf/Hi,
Give the full path of the log file to the FileWriter. Such as;
FileWriter salida = new FileWriter(response.encodeURL("/usr/local/tomcat/logs/testlogs/log.txt"));
nurettin -
How to write a Xml installation file to build web installer using IzPack.
Hai everyone,
I have got a problem in building a web installer using IzPack.I am getting this exception,when I am compiling my install.xml using a compile tool provided by IzPack soft.Eventhough I have not mentioned "packsinfo.xml" in my Xml installation file.
Fatal error :
null\packsinfo.xml (The system cannot find the path specified)
java.io.FileNotFoundException: null\packsinfo.xml (The system cannot find the path specified)
What went wrong??
It is very very urgent. Could anyone tell me how to write a Xml installation file for building web installer,please??
any help will be highly appreciated....
Thank you very much in advanceHi,
that is not really a java related question. Have you tried to find some IzPack support forum? I've never heard about it, so I can't help. -
How to write data to text file using external tables
can anybody tell how to write data to text file using external tables concept?
Hi,
Using external table u can load the data in your local table in database,
then using your local db table and UTL_FILE pacakge u can wrrite data to text file
external table
~~~~~~~~~~~
http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7002.htm#i2153251
UTL_FILE
~~~~~~~~~
http://download-east.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#sthref14093
Message was edited by:
Nicloei W
Message was edited by:
Nicloei W -
How to write code for save file directory?
how to write code for save file directory?
how to find usa timezone code using java swing?
i have some code help me
public class ItsInitializer {
private static boolean s_initialized = false;
private ItsInitializer() {
public static synchronized void initialize() {
if (!s_initialized) {
// Modifies default time zone, disables Daylight Saving Time.
TimeZone l_defaultTimeZone = TimeZone.getDefault();
int l_rawOffset = l_defaultTimeZone.getRawOffset();
String l_id = l_defaultTimeZone.getID();
SimpleTimeZone l_simpleTimeZone = new SimpleTimeZone(l_rawOffset,
l_id,
0,
0,
0,
0,
0,
0,
0,
0);
TimeZone.setDefault(l_simpleTimeZone);
s_initialized = true;
2.
long timeMillis = ...;
long time = timeMillis / 1000;
String seconds = Integer.toString((int)(time % 60));
String minutes = Integer.toString((int)((time % 3600) / 60));
String hours = Integer.toString((int)(time / 3600));
for (int i = 0; i < 2; i++) {
if (seconds.length() < 2) {
seconds = "0" + seconds;
if (minutes.length() < 2) {
minutes = "0" + minutes;
if (hours.length() < 2) {
hours = "0" + hours;
3.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Convert {
public String getDateTime(String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date());
* @param args
public static void main(String[] args) {
Convert con = new Convert();
System.out.println(con.getDateTime("hh:mm:ss"));
5.import java.text.SimpleDateFormat;
import java.util.Date;
public class Convert {
public String getDateTime(String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date());
* @param args
public static void main(String[] args) {
Convert con = new Convert();
System.out.println(con.getDateTime("hh:mm:ss"));
[ November 23, 2005: Mess
private Locale locale = Locale.US;
private static final String[] tzStrings = {
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
Date now = new Date();
for ( TimeZone z : zones) {
DateFormat df = new SimpleDateFormat("K:mm a,z", locale);
df.setTimeZone(z);
String result = df.format(now);
System.out.println(result);
String date="05/19/2008 04:30 AM (EST)";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa (z)");
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
long millis = sdf.parse(date).getTime();
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(new Date(millis)));
[ November 23, 2005: Mes -
Anyone know how to write to a RAW file format?
Hello,
Been trying to find out if there is any way to write a RAW format file from an array containing pixel values? Do I just use a file writer and save as *.raw?
Also, what information must I include beyond the pixel values?
Thanks!Well, I had found those already and they weren't of
too much help to my problem (how to actually create
the RAW file), but thanks.I'd imagine that you'd create the RAW file according to the specifications provided. The links provided give you information as to the format of the RAW file. In order to actually create the RAW file, you'd simply spit out the properly-formed data to a file (see a tutorial such as "Lesson: I/O: Reading and Writing (but no 'rithmetic)" for more info, if needed).
What additional help are you looking for? -
How to write and read Xml file from database if possible?
Hi all,
I need to read the .Xml file when receives from Source systems and write the data into the table as well as write in the.xml file thru reading the data from table as per the client needs. I am stranger to this area. Since, please provide some examples how to approach the same.
Thanks in advance !!
Regards.
Vissu.....The XML DB forum is better suited to your question.
It also has a FAQ which details how to read and shred XML into tables as well as other common XML based questions...
XML DB FAQ -
How to write a CLOB to file using UTF-8
I'm new to java and I have the following problem.
I need to write a CLOB to file using the UTF-8 characterset (I'm generating an xml file). My database characterset is WE8ISO8859P15.
I've tried the code below but the resulting output fails validation in an xml editor due to an 'invalid character' error :
create or replace
and compile
java source named "ClobUtil"
as
import java.io.*;
import java.lang.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
public class ClobUtil {
public static void save(CLOB clob, String filename) throws Exception
Connection conn = DriverManager.getConnection("jdbc:oracle:kprb:");
conn.setAutoCommit(false);
InputStream is = clob.getCharacterStream();
FileOutputStream os = new FileOutputStream(filename);
int size = clob.getChunkSize();
byte buffer[] = new byte[size];
int length;
while ((length = is.read(buffer, 0, size)) != -1) {
os.write(buffer, 0, length);
is.close();
os.close();
conn.close();
I see that the getCharacterStream() method returns a Unicode character stream but how do I output this to file ??
Thanks in advanceFile file = new File( "myfile.utf8" );
FileOutputStream fos = new FileOutputStream( file );
OutputStreamWriter osw = new
OutputStreamWriter( fos, "UTF8" );
Writer w = new BufferedWriter( osw );
PrintWriter out = new PrintWriter( w );
Or whatever you need. Note that this merely allows you to specify the encoding to be used in the output file, it does convert the encoding for you. I think in your case this will work since you already know the output stream will not contain the full range of UTF8 characters anyway. -
How to write data to existing file using spool command?
Hi,
I am calling a stored procedure from a shell script. This stored procedure is having a CLOB object as an OUT parameter. How to write the data in CLOB object a existing file which is there in my client system. Below is the shell and sql scripts.
Shell script
( echo "hello" ) > /root/file.txt
sqlplus -s $user/$pass@$tns @/root/proc.sql /root/file.txt << EOF
EOFSQL script
set pages 0
set trimspool off
set serveroutput off
set feedback off
set term off
set echo off
variable out CLOB
define file='&1'
begin
pack.proc(:out);
end;
spool &file
select :out from dual;
spool offThis code writes contents of the OUT variable to file.txt, but my existing data ('hello') is lost. Please help me.
I figured the it...Use append in the spool command... :)
Edited by: Balaji on Jul 19, 2012 8:55 PM>
Hi Balaji
I figured the it...Use append in the spool command... :Please mark the thread as answered as per the FAQ.
Paul... -
How to write data to xml file?
Hi,
I have done a project which read data from a web then write in log file.
Now i want to write data in xml file.
how to write?
i read some java and xml tutorial, quite quite difficult.
Who can give a simple example with some comments?
If you also give some tips on learning java web services, i will be very appreciated.
Thanks
Yang BinChoose Xerces2.4 to serialize the DOM object is an option.
javac XercesTest.java -classpath xmlParserAPIs.jar;xercesImpl.jar;.
java -classpath xmlParserAPIs.jar;xercesImpl.jar;. XercesTest test.xml
below is the source file: XercesTest.java
//JAXP
import javax.xml.parsers.*;
import org.w3c.dom.*;
//APACHE SERIALIZE FUNCTION
import org.apache.xml.serialize.*;
class XercesTest
public static void main(String[] args) throws Exception
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse( new File( args[0] ) );
File f = new File( "copy_of_"+ args[0] );
OutputFormat format = new OutputFormat("xml","UTF-8",true ) ;
FileOutputStream fout = new FileOutputStream( f );
XMLSerializer ser = new XMLSerializer(fout, format );
ser.serialize( doc );
hope it's helpful
land -
How to write newline character to file using bytes along with content
Hi All,
I need to write headers into the file using byte[]. I am creating the strings of header which will form the different rows in the file. I am new to java and would like to know how to embed new line character so that when the byte[] is written to file headers come in different rows.
like
hrd1:abcd
hdr2:1234
when i embed \n and \r in string and do getBytes() and write it to file, some boxes are written in the file and everything comes into single line.
Please advice me the correct way .
Thanks in advance.
Cheers!!
Puneetnot sure about it, but i was always told that "\r\n" meant "new line" on "lots of documents" whereas "\n" only or "\r" only were meaningless on some type of documents
-
How to write '\n' in text file instead of newline
Hello Everyone,
I am trying to write 'C:\DOCUME~1\nXXX\LOCALS~1\Temp' in a bat file using client_text_io but *'\n'* in the path is taken as a new line character and the path is broken into two lines and written to the file. Hence my bat file doesnt work. I would need to write '\n' in the file as there are many reports which has '\n' in the output. Please provide a solution for writing '\n' in the file without getting it converted to a new line.
DECLARE
out_file client_text_io.file_type;
BEGIN
:GLOBAL.TEMPDRIVE :=client_win_api_environment.get_environment_string('TEMP'); --output is 'C:\DOCUME~1\nXXX\LOCALS~1\Temp'
out_file := client_Text_IO.fopen(:GLOBAL.TEMPDRIVE||'\chkdirz.bat', 'w');
client_Text_IO.PutF(out_file,'chdir '||:GLOBAL.TEMPDRIVE||'\ \n');
client_Text_IO.PutF(out_file,'if EXIST '||:GLOBAL.TEMPDRIVE||'\EXFOL\ null goto batend \n');
client_Text_IO.PutF(out_file,'mkdir '||:GLOBAL.TEMPDRIVE||'\EXFOL \n');
client_Text_IO.PutF(out_file,':batend \n');
client_Text_IO.fclose(out_file);
synchronize;
CLIENT_host('cmd.exe /c '||:GLOBAL.TEMPDRIVE||'\chkdirz.bat',NO_SCREEN);
END;christian erlinger wrote:
When you want to print out an escape character in java (java is doing the work in client_text_io ), you'd need to escape it.
client_text_io.put_line(out_file, replace('your_path', '\','\\'));cheersI tried replacing \ with double slash but it just printed double slash in the bat file. again the path was broken into two lines.
file output
chdir C:\\DOCUME~1\
195969\\LOCALS~1\\Temp\
Edited by: rivas on Mar 21, 2011 6:03 AM -
How to Write data in Excel File using java
Hi
can anybody help me to write data in excel file
using java code
Thankx In AdvanceHow much are you willing to pay for that?
If you want it for free, http://jexcelapi.sourceforge.net/ -
How to write IPTC metadata to files without opening the file?
HI,
I'm trying to run a script (preferably in JS) that allows me to write metadata to a file. I can acheive this very easily by opening the file, but I'd need to batch process many large images, so opening them would cause severe slowness. The purpose of adding the metadata to the files is to search upon them in Bridge.
We're using CS5, but have CS6 if it's better to use.
My Script
// set current doc ref
var docRef = app.activeDocument;
// Set caption in active document
docRef.info.caption = "Some Meta-Data";
Do I need to use bridge to write the metadata without opening the file? Or can running the script in PS allow me to do so?
Thanks,
TomIts easy if you use XMP metadata.
app.activeDocument.info.caption (in photoshop script metadata)
and it is the same field as:
Dublin Core namespace
namespace: http://purl.org/dc/elements/1.1/
Property: description
you change description on XMP = you are changing the same image.info.caption
Your answer is here:
http://forums.adobe.com/message/5743730#5743730 -
How to write to an XML file from JDE batch application?
Hello everyone,
I need to write data from a batch application to an XML file. I don't know how to use the XML business functions.
I tried to use XML Publisher but the format is not the same as the client XML. The XML file has some customized format.
I need to do it manually with business functions and ER. Please help me out.
Some business functions I saw are Create XML document, XML Add element and XML Add attribute but the parameters are complex to
use.
Thank you very much.
Edited by: Lovvy on Sep 8, 2010 2:58 AMThe XML DB forum is better suited to your question.
It also has a FAQ which details how to read and shred XML into tables as well as other common XML based questions...
XML DB FAQ -
How to write content of the file under folder
Hi Experts,
I have following scenario, I have list of files under folder in local desktop(for eg D:\mani)
I have only filename, using this filename i want to search and get content of the particular file and write in some other location? how to do that? give your suggestions?
Regards,
P.ManivannanYou could go two ways here:
The first possibility requires that (a) you know what operating system you are working with, and (b) you only need to copy the file, and not do anything else with the contents of it. In this case, probably the easiest way to do this is to use a Runtime exec command for the file you want to copy:
java.lang.Runtime.getRuntime().exec( "cp D:\mani D:\mani2" );Otherwise, if you need your code to be portable, you can't assume anything about the operating system. Since java.io.File doesn't provide a copy method, you will need to read the entire contents of the file into the vm, and then write them out to a new file. Also, if you need to use the contents of your file in some other way, as well, then you also need to read the entire contents into the vm. In this second case, how you read the file may depend on what kind of data the file contains.
In general, the following code should work for you:
final FileInputSteam fis = new FileInputStream ( new File( "D:\mani" ) );
final FileOutputStream fos = new FileOutputStream( new File( "D:\mani2" ) );
final byte [] buf = new byte[ 1024 ];
int bytesRead;
while ( ( bytesRead = fis.read( buf ) ) != 0 )
fos.write( buf, 0, bytesRead );Don't forget to catch or throw IOException.
Hope this helps.
- Adam
Maybe you are looking for
-
Issues with activating iMessage
Howdy, I'm a new member of Apple support community. I bought a new iPhone 5S back in December 2013 and 15 days past it was stolen. I've done all that is neccesary to find this phone, set it to erase all data on www.icloud.com/#find. I've had icloud a
-
Hello, Can anyone tell me if premiere pro can make a 2 hour movie or longer?
Hello Can anyone tell me if premiere pro can make a 2 hour movie or longer?
-
Layout problem in screen painter
hi all, the screen is not appearing when i click 'layout' button in screen painter when i am enabling a wsp client proxy server. Is there any solution?
-
After changing spaces, most keys stop registering
I have a 5 year old Mac Pro running OS 10.6.8. I have spaces configured with four spaces, and the keyboard command to switch between spaces set as Ctrl-arrow. Most of the time this works as expected. However I've been having a periodic issue where, a
-
TAXINN AND TAXINJ difference ? AND Which is better ?
HI, Could u please explain difference between TAXINN AND TAXINJ ? AND Which is better ? And in which scenario they are used ? Regrds, Binayak